2
0

aoptx86.pas 418 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843
  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. interface
  21. uses
  22. globtype,
  23. cpubase,
  24. aasmtai,aasmcpu,
  25. cgbase,cgutils,
  26. aopt,aoptobj;
  27. type
  28. TOptsToCheck = (
  29. aoc_MovAnd2Mov_3
  30. );
  31. TX86AsmOptimizer = class(TAsmOptimizer)
  32. { some optimizations are very expensive to check, so the
  33. pre opt pass can be used to set some flags, depending on the found
  34. instructions if it is worth to check a certain optimization }
  35. OptsToCheck : set of TOptsToCheck;
  36. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  37. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  38. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  39. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  40. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  41. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  42. potentially allowing further optimisation (although it might need to know if
  43. it crossed a conditional jump. }
  44. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  45. {
  46. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  47. the use of a register by allocs/dealloc, so it can ignore calls.
  48. In the following example, GetNextInstructionUsingReg will return the second movq,
  49. GetNextInstructionUsingRegTrackingUse won't.
  50. movq %rdi,%rax
  51. # Register rdi released
  52. # Register rdi allocated
  53. movq %rax,%rdi
  54. While in this example:
  55. movq %rdi,%rax
  56. call proc
  57. movq %rdi,%rax
  58. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  59. won't.
  60. }
  61. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  62. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  63. private
  64. function SkipSimpleInstructions(var hp1: tai): Boolean;
  65. protected
  66. class function IsMOVZXAcceptable: Boolean; static; inline;
  67. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  68. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  69. { checks whether reading the value in reg1 depends on the value of reg2. This
  70. is very similar to SuperRegisterEquals, except it takes into account that
  71. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  72. depend on the value in AH). }
  73. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  74. { Replaces all references to AOldReg in a memory reference to ANewReg }
  75. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  76. { Replaces all references to AOldReg in an operand to ANewReg }
  77. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  78. { Replaces all references to AOldReg in an instruction to ANewReg,
  79. except where the register is being written }
  80. function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  81. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  82. or writes to a global symbol }
  83. class function IsRefSafe(const ref: PReference): Boolean; static; inline;
  84. { Returns true if the given MOV instruction can be safely converted to CMOV }
  85. class function CanBeCMOV(p : tai) : boolean; static;
  86. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  87. conversion was successful }
  88. function ConvertLEA(const p : taicpu): Boolean;
  89. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  90. procedure DebugMsg(const s : string; p : tai);inline;
  91. class function IsExitCode(p : tai) : boolean; static;
  92. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  93. procedure RemoveLastDeallocForFuncRes(p : tai);
  94. function DoSubAddOpt(var p : tai) : Boolean;
  95. function PrePeepholeOptSxx(var p : tai) : boolean;
  96. function PrePeepholeOptIMUL(var p : tai) : boolean;
  97. function PrePeepholeOptAND(var p : tai) : boolean;
  98. function OptPass1Test(var p: tai): boolean;
  99. function OptPass1Add(var p: tai): boolean;
  100. function OptPass1AND(var p : tai) : boolean;
  101. function OptPass1_V_MOVAP(var p : tai) : boolean;
  102. function OptPass1VOP(var p : tai) : boolean;
  103. function OptPass1MOV(var p : tai) : boolean;
  104. function OptPass1Movx(var p : tai) : boolean;
  105. function OptPass1MOVXX(var p : tai) : boolean;
  106. function OptPass1OP(var p : tai) : boolean;
  107. function OptPass1LEA(var p : tai) : boolean;
  108. function OptPass1Sub(var p : tai) : boolean;
  109. function OptPass1SHLSAL(var p : tai) : boolean;
  110. function OptPass1FSTP(var p : tai) : boolean;
  111. function OptPass1FLD(var p : tai) : boolean;
  112. function OptPass1Cmp(var p : tai) : boolean;
  113. function OptPass1PXor(var p : tai) : boolean;
  114. function OptPass1VPXor(var p: tai): boolean;
  115. function OptPass1Imul(var p : tai) : boolean;
  116. function OptPass1Jcc(var p : tai) : boolean;
  117. function OptPass1SHXX(var p: tai): boolean;
  118. function OptPass2Movx(var p : tai): Boolean;
  119. function OptPass2MOV(var p : tai) : boolean;
  120. function OptPass2Imul(var p : tai) : boolean;
  121. function OptPass2Jmp(var p : tai) : boolean;
  122. function OptPass2Jcc(var p : tai) : boolean;
  123. function OptPass2Lea(var p: tai): Boolean;
  124. function OptPass2SUB(var p: tai): Boolean;
  125. function OptPass2ADD(var p : tai): Boolean;
  126. function OptPass2SETcc(var p : tai) : boolean;
  127. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  128. function PostPeepholeOptMov(var p : tai) : Boolean;
  129. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  130. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  131. function PostPeepholeOptXor(var p : tai) : Boolean;
  132. {$endif}
  133. function PostPeepholeOptAnd(var p : tai) : boolean;
  134. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  135. function PostPeepholeOptCmp(var p : tai) : Boolean;
  136. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  137. function PostPeepholeOptCall(var p : tai) : Boolean;
  138. function PostPeepholeOptLea(var p : tai) : Boolean;
  139. function PostPeepholeOptPush(var p: tai): Boolean;
  140. function PostPeepholeOptShr(var p : tai) : boolean;
  141. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  142. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  143. procedure SwapMovCmp(var p, hp1: tai);
  144. { Processor-dependent reference optimisation }
  145. class procedure OptimizeRefs(var p: taicpu); static;
  146. end;
  147. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  148. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  149. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  150. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  151. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  152. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  153. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  154. {$if max_operands>2}
  155. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  156. {$endif max_operands>2}
  157. function RefsEqual(const r1, r2: treference): boolean;
  158. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  159. { returns true, if ref is a reference using only the registers passed as base and index
  160. and having an offset }
  161. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  162. implementation
  163. uses
  164. cutils,verbose,
  165. systems,
  166. globals,
  167. cpuinfo,
  168. procinfo,
  169. paramgr,
  170. aasmbase,
  171. aoptbase,aoptutils,
  172. symconst,symsym,
  173. cgx86,
  174. itcpugas;
  175. {$ifdef DEBUG_AOPTCPU}
  176. const
  177. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  178. {$else DEBUG_AOPTCPU}
  179. { Empty strings help the optimizer to remove string concatenations that won't
  180. ever appear to the user on release builds. [Kit] }
  181. const
  182. SPeepholeOptimization = '';
  183. {$endif DEBUG_AOPTCPU}
  184. LIST_STEP_SIZE = 4;
  185. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  186. begin
  187. result :=
  188. (instr.typ = ait_instruction) and
  189. (taicpu(instr).opcode = op) and
  190. ((opsize = []) or (taicpu(instr).opsize in opsize));
  191. end;
  192. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  193. begin
  194. result :=
  195. (instr.typ = ait_instruction) and
  196. ((taicpu(instr).opcode = op1) or
  197. (taicpu(instr).opcode = op2)
  198. ) and
  199. ((opsize = []) or (taicpu(instr).opsize in opsize));
  200. end;
  201. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  202. begin
  203. result :=
  204. (instr.typ = ait_instruction) and
  205. ((taicpu(instr).opcode = op1) or
  206. (taicpu(instr).opcode = op2) or
  207. (taicpu(instr).opcode = op3)
  208. ) and
  209. ((opsize = []) or (taicpu(instr).opsize in opsize));
  210. end;
  211. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  212. const opsize : topsizes) : boolean;
  213. var
  214. op : TAsmOp;
  215. begin
  216. result:=false;
  217. for op in ops do
  218. begin
  219. if (instr.typ = ait_instruction) and
  220. (taicpu(instr).opcode = op) and
  221. ((opsize = []) or (taicpu(instr).opsize in opsize)) then
  222. begin
  223. result:=true;
  224. exit;
  225. end;
  226. end;
  227. end;
  228. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  229. begin
  230. result := (oper.typ = top_reg) and (oper.reg = reg);
  231. end;
  232. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  233. begin
  234. result := (oper.typ = top_const) and (oper.val = a);
  235. end;
  236. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  237. begin
  238. result := oper1.typ = oper2.typ;
  239. if result then
  240. case oper1.typ of
  241. top_const:
  242. Result:=oper1.val = oper2.val;
  243. top_reg:
  244. Result:=oper1.reg = oper2.reg;
  245. top_ref:
  246. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  247. else
  248. internalerror(2013102801);
  249. end
  250. end;
  251. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  252. begin
  253. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  254. if result then
  255. case oper1.typ of
  256. top_const:
  257. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  258. top_reg:
  259. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  260. top_ref:
  261. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  262. else
  263. internalerror(2020052401);
  264. end
  265. end;
  266. function RefsEqual(const r1, r2: treference): boolean;
  267. begin
  268. RefsEqual :=
  269. (r1.offset = r2.offset) and
  270. (r1.segment = r2.segment) and (r1.base = r2.base) and
  271. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  272. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  273. (r1.relsymbol = r2.relsymbol) and
  274. (r1.volatility=[]) and
  275. (r2.volatility=[]);
  276. end;
  277. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  278. begin
  279. Result:=(ref.offset=0) and
  280. (ref.scalefactor in [0,1]) and
  281. (ref.segment=NR_NO) and
  282. (ref.symbol=nil) and
  283. (ref.relsymbol=nil) and
  284. ((base=NR_INVALID) or
  285. (ref.base=base)) and
  286. ((index=NR_INVALID) or
  287. (ref.index=index)) and
  288. (ref.volatility=[]);
  289. end;
  290. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  291. begin
  292. Result:=(ref.scalefactor in [0,1]) and
  293. (ref.segment=NR_NO) and
  294. (ref.symbol=nil) and
  295. (ref.relsymbol=nil) and
  296. ((base=NR_INVALID) or
  297. (ref.base=base)) and
  298. ((index=NR_INVALID) or
  299. (ref.index=index)) and
  300. (ref.volatility=[]);
  301. end;
  302. function InstrReadsFlags(p: tai): boolean;
  303. begin
  304. InstrReadsFlags := true;
  305. case p.typ of
  306. ait_instruction:
  307. if InsProp[taicpu(p).opcode].Ch*
  308. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  309. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  310. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  311. exit;
  312. ait_label:
  313. exit;
  314. else
  315. ;
  316. end;
  317. InstrReadsFlags := false;
  318. end;
  319. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  320. begin
  321. Next:=Current;
  322. repeat
  323. Result:=GetNextInstruction(Next,Next);
  324. until not (Result) or
  325. not(cs_opt_level3 in current_settings.optimizerswitches) or
  326. (Next.typ<>ait_instruction) or
  327. RegInInstruction(reg,Next) or
  328. is_calljmp(taicpu(Next).opcode);
  329. end;
  330. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  331. begin
  332. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  333. Next := Current;
  334. repeat
  335. Result := GetNextInstruction(Next,Next);
  336. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  337. if is_calljmpuncond(taicpu(Next).opcode) then
  338. begin
  339. Result := False;
  340. Exit;
  341. end
  342. else
  343. CrossJump := True;
  344. until not Result or
  345. not (cs_opt_level3 in current_settings.optimizerswitches) or
  346. (Next.typ <> ait_instruction) or
  347. RegInInstruction(reg,Next);
  348. end;
  349. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  350. begin
  351. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  352. begin
  353. Result:=GetNextInstruction(Current,Next);
  354. exit;
  355. end;
  356. Next:=tai(Current.Next);
  357. Result:=false;
  358. while assigned(Next) do
  359. begin
  360. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  361. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  362. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  363. exit
  364. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  365. begin
  366. Result:=true;
  367. exit;
  368. end;
  369. Next:=tai(Next.Next);
  370. end;
  371. end;
  372. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  373. begin
  374. Result:=RegReadByInstruction(reg,hp);
  375. end;
  376. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  377. var
  378. p: taicpu;
  379. opcount: longint;
  380. begin
  381. RegReadByInstruction := false;
  382. if hp.typ <> ait_instruction then
  383. exit;
  384. p := taicpu(hp);
  385. case p.opcode of
  386. A_CALL:
  387. regreadbyinstruction := true;
  388. A_IMUL:
  389. case p.ops of
  390. 1:
  391. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  392. (
  393. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  394. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  395. );
  396. 2,3:
  397. regReadByInstruction :=
  398. reginop(reg,p.oper[0]^) or
  399. reginop(reg,p.oper[1]^);
  400. else
  401. InternalError(2019112801);
  402. end;
  403. A_MUL:
  404. begin
  405. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  406. (
  407. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  408. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  409. );
  410. end;
  411. A_IDIV,A_DIV:
  412. begin
  413. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  414. (
  415. (getregtype(reg)=R_INTREGISTER) and
  416. (
  417. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  418. )
  419. );
  420. end;
  421. else
  422. begin
  423. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  424. begin
  425. RegReadByInstruction := false;
  426. exit;
  427. end;
  428. for opcount := 0 to p.ops-1 do
  429. if (p.oper[opCount]^.typ = top_ref) and
  430. RegInRef(reg,p.oper[opcount]^.ref^) then
  431. begin
  432. RegReadByInstruction := true;
  433. exit
  434. end;
  435. { special handling for SSE MOVSD }
  436. if (p.opcode=A_MOVSD) and (p.ops>0) then
  437. begin
  438. if p.ops<>2 then
  439. internalerror(2017042702);
  440. regReadByInstruction := reginop(reg,p.oper[0]^) or
  441. (
  442. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  443. );
  444. exit;
  445. end;
  446. with insprop[p.opcode] do
  447. begin
  448. if getregtype(reg)=R_INTREGISTER then
  449. begin
  450. case getsupreg(reg) of
  451. RS_EAX:
  452. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  453. begin
  454. RegReadByInstruction := true;
  455. exit
  456. end;
  457. RS_ECX:
  458. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  459. begin
  460. RegReadByInstruction := true;
  461. exit
  462. end;
  463. RS_EDX:
  464. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  465. begin
  466. RegReadByInstruction := true;
  467. exit
  468. end;
  469. RS_EBX:
  470. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  471. begin
  472. RegReadByInstruction := true;
  473. exit
  474. end;
  475. RS_ESP:
  476. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  477. begin
  478. RegReadByInstruction := true;
  479. exit
  480. end;
  481. RS_EBP:
  482. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  483. begin
  484. RegReadByInstruction := true;
  485. exit
  486. end;
  487. RS_ESI:
  488. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  489. begin
  490. RegReadByInstruction := true;
  491. exit
  492. end;
  493. RS_EDI:
  494. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  495. begin
  496. RegReadByInstruction := true;
  497. exit
  498. end;
  499. end;
  500. end;
  501. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  502. begin
  503. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  504. begin
  505. case p.condition of
  506. C_A,C_NBE, { CF=0 and ZF=0 }
  507. C_BE,C_NA: { CF=1 or ZF=1 }
  508. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  509. C_AE,C_NB,C_NC, { CF=0 }
  510. C_B,C_NAE,C_C: { CF=1 }
  511. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  512. C_NE,C_NZ, { ZF=0 }
  513. C_E,C_Z: { ZF=1 }
  514. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  515. C_G,C_NLE, { ZF=0 and SF=OF }
  516. C_LE,C_NG: { ZF=1 or SF<>OF }
  517. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  518. C_GE,C_NL, { SF=OF }
  519. C_L,C_NGE: { SF<>OF }
  520. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  521. C_NO, { OF=0 }
  522. C_O: { OF=1 }
  523. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  524. C_NP,C_PO, { PF=0 }
  525. C_P,C_PE: { PF=1 }
  526. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  527. C_NS, { SF=0 }
  528. C_S: { SF=1 }
  529. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  530. else
  531. internalerror(2017042701);
  532. end;
  533. if RegReadByInstruction then
  534. exit;
  535. end;
  536. case getsubreg(reg) of
  537. R_SUBW,R_SUBD,R_SUBQ:
  538. RegReadByInstruction :=
  539. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  540. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  541. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  542. R_SUBFLAGCARRY:
  543. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  544. R_SUBFLAGPARITY:
  545. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  546. R_SUBFLAGAUXILIARY:
  547. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  548. R_SUBFLAGZERO:
  549. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  550. R_SUBFLAGSIGN:
  551. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  552. R_SUBFLAGOVERFLOW:
  553. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  554. R_SUBFLAGINTERRUPT:
  555. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  556. R_SUBFLAGDIRECTION:
  557. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  558. else
  559. internalerror(2017042601);
  560. end;
  561. exit;
  562. end;
  563. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  564. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  565. (p.oper[0]^.reg=p.oper[1]^.reg) then
  566. exit;
  567. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  568. begin
  569. RegReadByInstruction := true;
  570. exit
  571. end;
  572. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  573. begin
  574. RegReadByInstruction := true;
  575. exit
  576. end;
  577. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  578. begin
  579. RegReadByInstruction := true;
  580. exit
  581. end;
  582. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  583. begin
  584. RegReadByInstruction := true;
  585. exit
  586. end;
  587. end;
  588. end;
  589. end;
  590. end;
  591. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  592. begin
  593. result:=false;
  594. if p1.typ<>ait_instruction then
  595. exit;
  596. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  597. exit(true);
  598. if (getregtype(reg)=R_INTREGISTER) and
  599. { change information for xmm movsd are not correct }
  600. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  601. begin
  602. case getsupreg(reg) of
  603. { RS_EAX = RS_RAX on x86-64 }
  604. RS_EAX:
  605. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  606. RS_ECX:
  607. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  608. RS_EDX:
  609. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  610. RS_EBX:
  611. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  612. RS_ESP:
  613. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  614. RS_EBP:
  615. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  616. RS_ESI:
  617. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  618. RS_EDI:
  619. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  620. else
  621. ;
  622. end;
  623. if result then
  624. exit;
  625. end
  626. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  627. begin
  628. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  629. exit(true);
  630. case getsubreg(reg) of
  631. R_SUBFLAGCARRY:
  632. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  633. R_SUBFLAGPARITY:
  634. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  635. R_SUBFLAGAUXILIARY:
  636. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  637. R_SUBFLAGZERO:
  638. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  639. R_SUBFLAGSIGN:
  640. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  641. R_SUBFLAGOVERFLOW:
  642. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  643. R_SUBFLAGINTERRUPT:
  644. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  645. R_SUBFLAGDIRECTION:
  646. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  647. else
  648. ;
  649. end;
  650. if result then
  651. exit;
  652. end
  653. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  654. exit(true);
  655. Result:=inherited RegInInstruction(Reg, p1);
  656. end;
  657. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  658. begin
  659. Result := False;
  660. if p1.typ <> ait_instruction then
  661. exit;
  662. with insprop[taicpu(p1).opcode] do
  663. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  664. begin
  665. case getsubreg(reg) of
  666. R_SUBW,R_SUBD,R_SUBQ:
  667. Result :=
  668. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  669. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  670. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  671. R_SUBFLAGCARRY:
  672. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  673. R_SUBFLAGPARITY:
  674. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  675. R_SUBFLAGAUXILIARY:
  676. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  677. R_SUBFLAGZERO:
  678. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  679. R_SUBFLAGSIGN:
  680. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  681. R_SUBFLAGOVERFLOW:
  682. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  683. R_SUBFLAGINTERRUPT:
  684. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  685. R_SUBFLAGDIRECTION:
  686. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  687. else
  688. internalerror(2017042602);
  689. end;
  690. exit;
  691. end;
  692. case taicpu(p1).opcode of
  693. A_CALL:
  694. { We could potentially set Result to False if the register in
  695. question is non-volatile for the subroutine's calling convention,
  696. but this would require detecting the calling convention in use and
  697. also assuming that the routine doesn't contain malformed assembly
  698. language, for example... so it could only be done under -O4 as it
  699. would be considered a side-effect. [Kit] }
  700. Result := True;
  701. A_MOVSD:
  702. { special handling for SSE MOVSD }
  703. if (taicpu(p1).ops>0) then
  704. begin
  705. if taicpu(p1).ops<>2 then
  706. internalerror(2017042703);
  707. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  708. end;
  709. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  710. so fix it here (FK)
  711. }
  712. A_VMOVSS,
  713. A_VMOVSD:
  714. begin
  715. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  716. exit;
  717. end;
  718. A_IMUL:
  719. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  720. else
  721. ;
  722. end;
  723. if Result then
  724. exit;
  725. with insprop[taicpu(p1).opcode] do
  726. begin
  727. if getregtype(reg)=R_INTREGISTER then
  728. begin
  729. case getsupreg(reg) of
  730. RS_EAX:
  731. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  732. begin
  733. Result := True;
  734. exit
  735. end;
  736. RS_ECX:
  737. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  738. begin
  739. Result := True;
  740. exit
  741. end;
  742. RS_EDX:
  743. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  744. begin
  745. Result := True;
  746. exit
  747. end;
  748. RS_EBX:
  749. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  750. begin
  751. Result := True;
  752. exit
  753. end;
  754. RS_ESP:
  755. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  756. begin
  757. Result := True;
  758. exit
  759. end;
  760. RS_EBP:
  761. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  762. begin
  763. Result := True;
  764. exit
  765. end;
  766. RS_ESI:
  767. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  768. begin
  769. Result := True;
  770. exit
  771. end;
  772. RS_EDI:
  773. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  774. begin
  775. Result := True;
  776. exit
  777. end;
  778. end;
  779. end;
  780. if ([CH_RWOP1,CH_WOP1,CH_MOP1]*Ch<>[]) and reginop(reg,taicpu(p1).oper[0]^) then
  781. begin
  782. Result := true;
  783. exit
  784. end;
  785. if ([Ch_RWOP2,Ch_WOP2,Ch_MOP2]*Ch<>[]) and reginop(reg,taicpu(p1).oper[1]^) then
  786. begin
  787. Result := true;
  788. exit
  789. end;
  790. if ([Ch_RWOP3,Ch_WOP3,Ch_MOP3]*Ch<>[]) and reginop(reg,taicpu(p1).oper[2]^) then
  791. begin
  792. Result := true;
  793. exit
  794. end;
  795. if ([Ch_RWOP4,Ch_WOP4,Ch_MOP4]*Ch<>[]) and reginop(reg,taicpu(p1).oper[3]^) then
  796. begin
  797. Result := true;
  798. exit
  799. end;
  800. end;
  801. end;
  802. {$ifdef DEBUG_AOPTCPU}
  803. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  804. begin
  805. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  806. end;
  807. function debug_tostr(i: tcgint): string; inline;
  808. begin
  809. Result := tostr(i);
  810. end;
  811. function debug_regname(r: TRegister): string; inline;
  812. begin
  813. Result := '%' + std_regname(r);
  814. end;
  815. { Debug output function - creates a string representation of an operator }
  816. function debug_operstr(oper: TOper): string;
  817. begin
  818. case oper.typ of
  819. top_const:
  820. Result := '$' + debug_tostr(oper.val);
  821. top_reg:
  822. Result := debug_regname(oper.reg);
  823. top_ref:
  824. begin
  825. if oper.ref^.offset <> 0 then
  826. Result := debug_tostr(oper.ref^.offset) + '('
  827. else
  828. Result := '(';
  829. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  830. begin
  831. Result := Result + debug_regname(oper.ref^.base);
  832. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  833. Result := Result + ',' + debug_regname(oper.ref^.index);
  834. end
  835. else
  836. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  837. Result := Result + debug_regname(oper.ref^.index);
  838. if (oper.ref^.scalefactor > 1) then
  839. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  840. else
  841. Result := Result + ')';
  842. end;
  843. else
  844. Result := '[UNKNOWN]';
  845. end;
  846. end;
  847. function debug_op2str(opcode: tasmop): string; inline;
  848. begin
  849. Result := std_op2str[opcode];
  850. end;
  851. function debug_opsize2str(opsize: topsize): string; inline;
  852. begin
  853. Result := gas_opsize2str[opsize];
  854. end;
  855. {$else DEBUG_AOPTCPU}
  856. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  857. begin
  858. end;
  859. function debug_tostr(i: tcgint): string; inline;
  860. begin
  861. Result := '';
  862. end;
  863. function debug_regname(r: TRegister): string; inline;
  864. begin
  865. Result := '';
  866. end;
  867. function debug_operstr(oper: TOper): string; inline;
  868. begin
  869. Result := '';
  870. end;
  871. function debug_op2str(opcode: tasmop): string; inline;
  872. begin
  873. Result := '';
  874. end;
  875. function debug_opsize2str(opsize: topsize): string; inline;
  876. begin
  877. Result := '';
  878. end;
  879. {$endif DEBUG_AOPTCPU}
  880. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  881. begin
  882. {$ifdef x86_64}
  883. { Always fine on x86-64 }
  884. Result := True;
  885. {$else x86_64}
  886. Result :=
  887. {$ifdef i8086}
  888. (current_settings.cputype >= cpu_386) and
  889. {$endif i8086}
  890. (
  891. { Always accept if optimising for size }
  892. (cs_opt_size in current_settings.optimizerswitches) or
  893. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  894. (current_settings.optimizecputype >= cpu_Pentium2)
  895. );
  896. {$endif x86_64}
  897. end;
  898. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  899. begin
  900. if not SuperRegistersEqual(reg1,reg2) then
  901. exit(false);
  902. if getregtype(reg1)<>R_INTREGISTER then
  903. exit(true); {because SuperRegisterEqual is true}
  904. case getsubreg(reg1) of
  905. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  906. higher, it preserves the high bits, so the new value depends on
  907. reg2's previous value. In other words, it is equivalent to doing:
  908. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  909. R_SUBL:
  910. exit(getsubreg(reg2)=R_SUBL);
  911. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  912. higher, it actually does a:
  913. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  914. R_SUBH:
  915. exit(getsubreg(reg2)=R_SUBH);
  916. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  917. bits of reg2:
  918. reg2 := (reg2 and $ffff0000) or word(reg1); }
  919. R_SUBW:
  920. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  921. { a write to R_SUBD always overwrites every other subregister,
  922. because it clears the high 32 bits of R_SUBQ on x86_64 }
  923. R_SUBD,
  924. R_SUBQ:
  925. exit(true);
  926. else
  927. internalerror(2017042801);
  928. end;
  929. end;
  930. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  931. begin
  932. if not SuperRegistersEqual(reg1,reg2) then
  933. exit(false);
  934. if getregtype(reg1)<>R_INTREGISTER then
  935. exit(true); {because SuperRegisterEqual is true}
  936. case getsubreg(reg1) of
  937. R_SUBL:
  938. exit(getsubreg(reg2)<>R_SUBH);
  939. R_SUBH:
  940. exit(getsubreg(reg2)<>R_SUBL);
  941. R_SUBW,
  942. R_SUBD,
  943. R_SUBQ:
  944. exit(true);
  945. else
  946. internalerror(2017042802);
  947. end;
  948. end;
  949. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  950. var
  951. hp1 : tai;
  952. l : TCGInt;
  953. begin
  954. result:=false;
  955. { changes the code sequence
  956. shr/sar const1, x
  957. shl const2, x
  958. to
  959. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  960. if GetNextInstruction(p, hp1) and
  961. MatchInstruction(hp1,A_SHL,[]) and
  962. (taicpu(p).oper[0]^.typ = top_const) and
  963. (taicpu(hp1).oper[0]^.typ = top_const) and
  964. (taicpu(hp1).opsize = taicpu(p).opsize) and
  965. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  966. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  967. begin
  968. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  969. not(cs_opt_size in current_settings.optimizerswitches) then
  970. begin
  971. { shr/sar const1, %reg
  972. shl const2, %reg
  973. with const1 > const2 }
  974. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  975. taicpu(hp1).opcode := A_AND;
  976. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  977. case taicpu(p).opsize Of
  978. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  979. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  980. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  981. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  982. else
  983. Internalerror(2017050703)
  984. end;
  985. end
  986. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  987. not(cs_opt_size in current_settings.optimizerswitches) then
  988. begin
  989. { shr/sar const1, %reg
  990. shl const2, %reg
  991. with const1 < const2 }
  992. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  993. taicpu(p).opcode := A_AND;
  994. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  995. case taicpu(p).opsize Of
  996. S_B: taicpu(p).loadConst(0,l Xor $ff);
  997. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  998. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  999. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1000. else
  1001. Internalerror(2017050702)
  1002. end;
  1003. end
  1004. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1005. begin
  1006. { shr/sar const1, %reg
  1007. shl const2, %reg
  1008. with const1 = const2 }
  1009. taicpu(p).opcode := A_AND;
  1010. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1011. case taicpu(p).opsize Of
  1012. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1013. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1014. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1015. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1016. else
  1017. Internalerror(2017050701)
  1018. end;
  1019. RemoveInstruction(hp1);
  1020. end;
  1021. end;
  1022. end;
  1023. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1024. var
  1025. opsize : topsize;
  1026. hp1 : tai;
  1027. tmpref : treference;
  1028. ShiftValue : Cardinal;
  1029. BaseValue : TCGInt;
  1030. begin
  1031. result:=false;
  1032. opsize:=taicpu(p).opsize;
  1033. { changes certain "imul const, %reg"'s to lea sequences }
  1034. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1035. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1036. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1037. if (taicpu(p).oper[0]^.val = 1) then
  1038. if (taicpu(p).ops = 2) then
  1039. { remove "imul $1, reg" }
  1040. begin
  1041. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1042. Result := RemoveCurrentP(p);
  1043. end
  1044. else
  1045. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1046. begin
  1047. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1048. InsertLLItem(p.previous, p.next, hp1);
  1049. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1050. p.free;
  1051. p := hp1;
  1052. end
  1053. else if ((taicpu(p).ops <= 2) or
  1054. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1055. not(cs_opt_size in current_settings.optimizerswitches) and
  1056. (not(GetNextInstruction(p, hp1)) or
  1057. not((tai(hp1).typ = ait_instruction) and
  1058. ((taicpu(hp1).opcode=A_Jcc) and
  1059. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1060. begin
  1061. {
  1062. imul X, reg1, reg2 to
  1063. lea (reg1,reg1,Y), reg2
  1064. shl ZZ,reg2
  1065. imul XX, reg1 to
  1066. lea (reg1,reg1,YY), reg1
  1067. shl ZZ,reg2
  1068. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1069. it does not exist as a separate optimization target in FPC though.
  1070. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1071. at most two zeros
  1072. }
  1073. reference_reset(tmpref,1,[]);
  1074. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1075. begin
  1076. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1077. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1078. TmpRef.base := taicpu(p).oper[1]^.reg;
  1079. TmpRef.index := taicpu(p).oper[1]^.reg;
  1080. if not(BaseValue in [3,5,9]) then
  1081. Internalerror(2018110101);
  1082. TmpRef.ScaleFactor := BaseValue-1;
  1083. if (taicpu(p).ops = 2) then
  1084. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1085. else
  1086. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1087. AsmL.InsertAfter(hp1,p);
  1088. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1089. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1090. RemoveCurrentP(p, hp1);
  1091. if ShiftValue>0 then
  1092. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1093. end;
  1094. end;
  1095. end;
  1096. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1097. begin
  1098. Result := False;
  1099. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1100. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1101. begin
  1102. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1103. taicpu(p).opcode := A_MOV;
  1104. Result := True;
  1105. end;
  1106. end;
  1107. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1108. var
  1109. p: taicpu absolute hp;
  1110. i: Integer;
  1111. begin
  1112. Result := False;
  1113. if not assigned(hp) or
  1114. (hp.typ <> ait_instruction) then
  1115. Exit;
  1116. // p := taicpu(hp);
  1117. Prefetch(insprop[p.opcode]);
  1118. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1119. with insprop[p.opcode] do
  1120. begin
  1121. case getsubreg(reg) of
  1122. R_SUBW,R_SUBD,R_SUBQ:
  1123. Result:=
  1124. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1125. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1126. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1127. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1128. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1129. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1130. R_SUBFLAGCARRY:
  1131. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1132. R_SUBFLAGPARITY:
  1133. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1134. R_SUBFLAGAUXILIARY:
  1135. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1136. R_SUBFLAGZERO:
  1137. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1138. R_SUBFLAGSIGN:
  1139. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1140. R_SUBFLAGOVERFLOW:
  1141. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1142. R_SUBFLAGINTERRUPT:
  1143. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1144. R_SUBFLAGDIRECTION:
  1145. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1146. else
  1147. begin
  1148. writeln(getsubreg(reg));
  1149. internalerror(2017050501);
  1150. end;
  1151. end;
  1152. exit;
  1153. end;
  1154. { Handle special cases first }
  1155. case p.opcode of
  1156. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1157. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1158. begin
  1159. Result :=
  1160. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1161. (p.oper[1]^.typ = top_reg) and
  1162. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1163. (
  1164. (p.oper[0]^.typ = top_const) or
  1165. (
  1166. (p.oper[0]^.typ = top_reg) and
  1167. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1168. ) or (
  1169. (p.oper[0]^.typ = top_ref) and
  1170. not RegInRef(reg,p.oper[0]^.ref^)
  1171. )
  1172. );
  1173. end;
  1174. A_MUL, A_IMUL:
  1175. Result :=
  1176. (
  1177. (p.ops=3) and { IMUL only }
  1178. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1179. (
  1180. (
  1181. (p.oper[1]^.typ=top_reg) and
  1182. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1183. ) or (
  1184. (p.oper[1]^.typ=top_ref) and
  1185. not RegInRef(reg,p.oper[1]^.ref^)
  1186. )
  1187. )
  1188. ) or (
  1189. (
  1190. (p.ops=1) and
  1191. (
  1192. (
  1193. (
  1194. (p.oper[0]^.typ=top_reg) and
  1195. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1196. )
  1197. ) or (
  1198. (p.oper[0]^.typ=top_ref) and
  1199. not RegInRef(reg,p.oper[0]^.ref^)
  1200. )
  1201. ) and (
  1202. (
  1203. (p.opsize=S_B) and
  1204. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1205. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1206. ) or (
  1207. (p.opsize=S_W) and
  1208. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1209. ) or (
  1210. (p.opsize=S_L) and
  1211. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1212. {$ifdef x86_64}
  1213. ) or (
  1214. (p.opsize=S_Q) and
  1215. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1216. {$endif x86_64}
  1217. )
  1218. )
  1219. )
  1220. );
  1221. A_CBW:
  1222. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1223. {$ifndef x86_64}
  1224. A_LDS:
  1225. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1226. A_LES:
  1227. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1228. {$endif not x86_64}
  1229. A_LFS:
  1230. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1231. A_LGS:
  1232. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1233. A_LSS:
  1234. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1235. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1236. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1237. A_LODSB:
  1238. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1239. A_LODSW:
  1240. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1241. {$ifdef x86_64}
  1242. A_LODSQ:
  1243. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1244. {$endif x86_64}
  1245. A_LODSD:
  1246. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1247. A_FSTSW, A_FNSTSW:
  1248. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1249. else
  1250. begin
  1251. with insprop[p.opcode] do
  1252. begin
  1253. if (
  1254. { xor %reg,%reg etc. is classed as a new value }
  1255. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1256. MatchOpType(p, top_reg, top_reg) and
  1257. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1258. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1259. ) then
  1260. begin
  1261. Result := True;
  1262. Exit;
  1263. end;
  1264. { Make sure the entire register is overwritten }
  1265. if (getregtype(reg) = R_INTREGISTER) then
  1266. begin
  1267. if (p.ops > 0) then
  1268. begin
  1269. if RegInOp(reg, p.oper[0]^) then
  1270. begin
  1271. if (p.oper[0]^.typ = top_ref) then
  1272. begin
  1273. if RegInRef(reg, p.oper[0]^.ref^) then
  1274. begin
  1275. Result := False;
  1276. Exit;
  1277. end;
  1278. end
  1279. else if (p.oper[0]^.typ = top_reg) then
  1280. begin
  1281. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1282. begin
  1283. Result := False;
  1284. Exit;
  1285. end
  1286. else if ([Ch_WOp1]*Ch<>[]) then
  1287. begin
  1288. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1289. Result := True
  1290. else
  1291. begin
  1292. Result := False;
  1293. Exit;
  1294. end;
  1295. end;
  1296. end;
  1297. end;
  1298. if (p.ops > 1) then
  1299. begin
  1300. if RegInOp(reg, p.oper[1]^) then
  1301. begin
  1302. if (p.oper[1]^.typ = top_ref) then
  1303. begin
  1304. if RegInRef(reg, p.oper[1]^.ref^) then
  1305. begin
  1306. Result := False;
  1307. Exit;
  1308. end;
  1309. end
  1310. else if (p.oper[1]^.typ = top_reg) then
  1311. begin
  1312. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1313. begin
  1314. Result := False;
  1315. Exit;
  1316. end
  1317. else if ([Ch_WOp2]*Ch<>[]) then
  1318. begin
  1319. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1320. Result := True
  1321. else
  1322. begin
  1323. Result := False;
  1324. Exit;
  1325. end;
  1326. end;
  1327. end;
  1328. end;
  1329. if (p.ops > 2) then
  1330. begin
  1331. if RegInOp(reg, p.oper[2]^) then
  1332. begin
  1333. if (p.oper[2]^.typ = top_ref) then
  1334. begin
  1335. if RegInRef(reg, p.oper[2]^.ref^) then
  1336. begin
  1337. Result := False;
  1338. Exit;
  1339. end;
  1340. end
  1341. else if (p.oper[2]^.typ = top_reg) then
  1342. begin
  1343. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1344. begin
  1345. Result := False;
  1346. Exit;
  1347. end
  1348. else if ([Ch_WOp3]*Ch<>[]) then
  1349. begin
  1350. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1351. Result := True
  1352. else
  1353. begin
  1354. Result := False;
  1355. Exit;
  1356. end;
  1357. end;
  1358. end;
  1359. end;
  1360. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1361. begin
  1362. if (p.oper[3]^.typ = top_ref) then
  1363. begin
  1364. if RegInRef(reg, p.oper[3]^.ref^) then
  1365. begin
  1366. Result := False;
  1367. Exit;
  1368. end;
  1369. end
  1370. else if (p.oper[3]^.typ = top_reg) then
  1371. begin
  1372. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1373. begin
  1374. Result := False;
  1375. Exit;
  1376. end
  1377. else if ([Ch_WOp4]*Ch<>[]) then
  1378. begin
  1379. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1380. Result := True
  1381. else
  1382. begin
  1383. Result := False;
  1384. Exit;
  1385. end;
  1386. end;
  1387. end;
  1388. end;
  1389. end;
  1390. end;
  1391. end;
  1392. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1393. case getsupreg(reg) of
  1394. RS_EAX:
  1395. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1396. begin
  1397. Result := True;
  1398. Exit;
  1399. end;
  1400. RS_ECX:
  1401. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1402. begin
  1403. Result := True;
  1404. Exit;
  1405. end;
  1406. RS_EDX:
  1407. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1408. begin
  1409. Result := True;
  1410. Exit;
  1411. end;
  1412. RS_EBX:
  1413. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1414. begin
  1415. Result := True;
  1416. Exit;
  1417. end;
  1418. RS_ESP:
  1419. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1420. begin
  1421. Result := True;
  1422. Exit;
  1423. end;
  1424. RS_EBP:
  1425. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1426. begin
  1427. Result := True;
  1428. Exit;
  1429. end;
  1430. RS_ESI:
  1431. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1432. begin
  1433. Result := True;
  1434. Exit;
  1435. end;
  1436. RS_EDI:
  1437. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1438. begin
  1439. Result := True;
  1440. Exit;
  1441. end;
  1442. else
  1443. ;
  1444. end;
  1445. end;
  1446. end;
  1447. end;
  1448. end;
  1449. end;
  1450. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1451. var
  1452. hp2,hp3 : tai;
  1453. begin
  1454. { some x86-64 issue a NOP before the real exit code }
  1455. if MatchInstruction(p,A_NOP,[]) then
  1456. GetNextInstruction(p,p);
  1457. result:=assigned(p) and (p.typ=ait_instruction) and
  1458. ((taicpu(p).opcode = A_RET) or
  1459. ((taicpu(p).opcode=A_LEAVE) and
  1460. GetNextInstruction(p,hp2) and
  1461. MatchInstruction(hp2,A_RET,[S_NO])
  1462. ) or
  1463. (((taicpu(p).opcode=A_LEA) and
  1464. MatchOpType(taicpu(p),top_ref,top_reg) and
  1465. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1466. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1467. ) and
  1468. GetNextInstruction(p,hp2) and
  1469. MatchInstruction(hp2,A_RET,[S_NO])
  1470. ) or
  1471. ((((taicpu(p).opcode=A_MOV) and
  1472. MatchOpType(taicpu(p),top_reg,top_reg) and
  1473. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1474. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1475. ((taicpu(p).opcode=A_LEA) and
  1476. MatchOpType(taicpu(p),top_ref,top_reg) and
  1477. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1478. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1479. )
  1480. ) and
  1481. GetNextInstruction(p,hp2) and
  1482. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1483. MatchOpType(taicpu(hp2),top_reg) and
  1484. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1485. GetNextInstruction(hp2,hp3) and
  1486. MatchInstruction(hp3,A_RET,[S_NO])
  1487. )
  1488. );
  1489. end;
  1490. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1491. begin
  1492. isFoldableArithOp := False;
  1493. case hp1.opcode of
  1494. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1495. isFoldableArithOp :=
  1496. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1497. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1498. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1499. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1500. (taicpu(hp1).oper[1]^.reg = reg);
  1501. A_INC,A_DEC,A_NEG,A_NOT:
  1502. isFoldableArithOp :=
  1503. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1504. (taicpu(hp1).oper[0]^.reg = reg);
  1505. else
  1506. ;
  1507. end;
  1508. end;
  1509. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1510. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1511. var
  1512. hp2: tai;
  1513. begin
  1514. hp2 := p;
  1515. repeat
  1516. hp2 := tai(hp2.previous);
  1517. if assigned(hp2) and
  1518. (hp2.typ = ait_regalloc) and
  1519. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1520. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1521. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1522. begin
  1523. RemoveInstruction(hp2);
  1524. break;
  1525. end;
  1526. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1527. end;
  1528. begin
  1529. case current_procinfo.procdef.returndef.typ of
  1530. arraydef,recorddef,pointerdef,
  1531. stringdef,enumdef,procdef,objectdef,errordef,
  1532. filedef,setdef,procvardef,
  1533. classrefdef,forwarddef:
  1534. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1535. orddef:
  1536. if current_procinfo.procdef.returndef.size <> 0 then
  1537. begin
  1538. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1539. { for int64/qword }
  1540. if current_procinfo.procdef.returndef.size = 8 then
  1541. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1542. end;
  1543. else
  1544. ;
  1545. end;
  1546. end;
  1547. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1548. var
  1549. hp1,hp2 : tai;
  1550. begin
  1551. result:=false;
  1552. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1553. begin
  1554. { vmova* reg1,reg1
  1555. =>
  1556. <nop> }
  1557. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1558. begin
  1559. RemoveCurrentP(p);
  1560. result:=true;
  1561. exit;
  1562. end
  1563. else if GetNextInstruction(p,hp1) then
  1564. begin
  1565. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1566. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1567. begin
  1568. { vmova* reg1,reg2
  1569. vmova* reg2,reg3
  1570. dealloc reg2
  1571. =>
  1572. vmova* reg1,reg3 }
  1573. TransferUsedRegs(TmpUsedRegs);
  1574. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1575. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1576. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1577. begin
  1578. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1579. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1580. RemoveInstruction(hp1);
  1581. result:=true;
  1582. exit;
  1583. end
  1584. { special case:
  1585. vmova* reg1,<op>
  1586. vmova* <op>,reg1
  1587. =>
  1588. vmova* reg1,<op> }
  1589. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1590. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1591. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1592. ) then
  1593. begin
  1594. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1595. RemoveInstruction(hp1);
  1596. result:=true;
  1597. exit;
  1598. end
  1599. end
  1600. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1601. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1602. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1603. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1604. ) and
  1605. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1606. begin
  1607. { vmova* reg1,reg2
  1608. vmovs* reg2,<op>
  1609. dealloc reg2
  1610. =>
  1611. vmovs* reg1,reg3 }
  1612. TransferUsedRegs(TmpUsedRegs);
  1613. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1614. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1615. begin
  1616. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1617. taicpu(p).opcode:=taicpu(hp1).opcode;
  1618. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1619. RemoveInstruction(hp1);
  1620. result:=true;
  1621. exit;
  1622. end
  1623. end;
  1624. end;
  1625. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1626. begin
  1627. if MatchInstruction(hp1,[A_VFMADDPD,
  1628. A_VFMADD132PD,
  1629. A_VFMADD132PS,
  1630. A_VFMADD132SD,
  1631. A_VFMADD132SS,
  1632. A_VFMADD213PD,
  1633. A_VFMADD213PS,
  1634. A_VFMADD213SD,
  1635. A_VFMADD213SS,
  1636. A_VFMADD231PD,
  1637. A_VFMADD231PS,
  1638. A_VFMADD231SD,
  1639. A_VFMADD231SS,
  1640. A_VFMADDSUB132PD,
  1641. A_VFMADDSUB132PS,
  1642. A_VFMADDSUB213PD,
  1643. A_VFMADDSUB213PS,
  1644. A_VFMADDSUB231PD,
  1645. A_VFMADDSUB231PS,
  1646. A_VFMSUB132PD,
  1647. A_VFMSUB132PS,
  1648. A_VFMSUB132SD,
  1649. A_VFMSUB132SS,
  1650. A_VFMSUB213PD,
  1651. A_VFMSUB213PS,
  1652. A_VFMSUB213SD,
  1653. A_VFMSUB213SS,
  1654. A_VFMSUB231PD,
  1655. A_VFMSUB231PS,
  1656. A_VFMSUB231SD,
  1657. A_VFMSUB231SS,
  1658. A_VFMSUBADD132PD,
  1659. A_VFMSUBADD132PS,
  1660. A_VFMSUBADD213PD,
  1661. A_VFMSUBADD213PS,
  1662. A_VFMSUBADD231PD,
  1663. A_VFMSUBADD231PS,
  1664. A_VFNMADD132PD,
  1665. A_VFNMADD132PS,
  1666. A_VFNMADD132SD,
  1667. A_VFNMADD132SS,
  1668. A_VFNMADD213PD,
  1669. A_VFNMADD213PS,
  1670. A_VFNMADD213SD,
  1671. A_VFNMADD213SS,
  1672. A_VFNMADD231PD,
  1673. A_VFNMADD231PS,
  1674. A_VFNMADD231SD,
  1675. A_VFNMADD231SS,
  1676. A_VFNMSUB132PD,
  1677. A_VFNMSUB132PS,
  1678. A_VFNMSUB132SD,
  1679. A_VFNMSUB132SS,
  1680. A_VFNMSUB213PD,
  1681. A_VFNMSUB213PS,
  1682. A_VFNMSUB213SD,
  1683. A_VFNMSUB213SS,
  1684. A_VFNMSUB231PD,
  1685. A_VFNMSUB231PS,
  1686. A_VFNMSUB231SD,
  1687. A_VFNMSUB231SS],[S_NO]) and
  1688. { we mix single and double opperations here because we assume that the compiler
  1689. generates vmovapd only after double operations and vmovaps only after single operations }
  1690. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1691. GetNextInstruction(hp1,hp2) and
  1692. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1693. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1694. begin
  1695. TransferUsedRegs(TmpUsedRegs);
  1696. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1697. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1698. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1699. begin
  1700. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1701. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1702. RemoveInstruction(hp2);
  1703. end;
  1704. end
  1705. else if (hp1.typ = ait_instruction) and
  1706. GetNextInstruction(hp1, hp2) and
  1707. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1708. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1709. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1710. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1711. (((taicpu(p).opcode=A_MOVAPS) and
  1712. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1713. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1714. ((taicpu(p).opcode=A_MOVAPD) and
  1715. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1716. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1717. ) then
  1718. { change
  1719. movapX reg,reg2
  1720. addsX/subsX/... reg3, reg2
  1721. movapX reg2,reg
  1722. to
  1723. addsX/subsX/... reg3,reg
  1724. }
  1725. begin
  1726. TransferUsedRegs(TmpUsedRegs);
  1727. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1728. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1729. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1730. begin
  1731. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1732. debug_op2str(taicpu(p).opcode)+' '+
  1733. debug_op2str(taicpu(hp1).opcode)+' '+
  1734. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1735. { we cannot eliminate the first move if
  1736. the operations uses the same register for source and dest }
  1737. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1738. RemoveCurrentP(p, nil);
  1739. p:=hp1;
  1740. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1741. RemoveInstruction(hp2);
  1742. result:=true;
  1743. end;
  1744. end;
  1745. end;
  1746. end;
  1747. end;
  1748. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1749. var
  1750. hp1 : tai;
  1751. begin
  1752. result:=false;
  1753. { replace
  1754. V<Op>X %mreg1,%mreg2,%mreg3
  1755. VMovX %mreg3,%mreg4
  1756. dealloc %mreg3
  1757. by
  1758. V<Op>X %mreg1,%mreg2,%mreg4
  1759. ?
  1760. }
  1761. if GetNextInstruction(p,hp1) and
  1762. { we mix single and double operations here because we assume that the compiler
  1763. generates vmovapd only after double operations and vmovaps only after single operations }
  1764. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1765. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1766. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1767. begin
  1768. TransferUsedRegs(TmpUsedRegs);
  1769. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1770. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1771. begin
  1772. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1773. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1774. RemoveInstruction(hp1);
  1775. result:=true;
  1776. end;
  1777. end;
  1778. end;
  1779. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1780. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1781. begin
  1782. Result := False;
  1783. { For safety reasons, only check for exact register matches }
  1784. { Check base register }
  1785. if (ref.base = AOldReg) then
  1786. begin
  1787. ref.base := ANewReg;
  1788. Result := True;
  1789. end;
  1790. { Check index register }
  1791. if (ref.index = AOldReg) then
  1792. begin
  1793. ref.index := ANewReg;
  1794. Result := True;
  1795. end;
  1796. end;
  1797. { Replaces all references to AOldReg in an operand to ANewReg }
  1798. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1799. var
  1800. OldSupReg, NewSupReg: TSuperRegister;
  1801. OldSubReg, NewSubReg: TSubRegister;
  1802. OldRegType: TRegisterType;
  1803. ThisOper: POper;
  1804. begin
  1805. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1806. Result := False;
  1807. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1808. InternalError(2020011801);
  1809. OldSupReg := getsupreg(AOldReg);
  1810. OldSubReg := getsubreg(AOldReg);
  1811. OldRegType := getregtype(AOldReg);
  1812. NewSupReg := getsupreg(ANewReg);
  1813. NewSubReg := getsubreg(ANewReg);
  1814. if OldRegType <> getregtype(ANewReg) then
  1815. InternalError(2020011802);
  1816. if OldSubReg <> NewSubReg then
  1817. InternalError(2020011803);
  1818. case ThisOper^.typ of
  1819. top_reg:
  1820. if (
  1821. (ThisOper^.reg = AOldReg) or
  1822. (
  1823. (OldRegType = R_INTREGISTER) and
  1824. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1825. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1826. (
  1827. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1828. {$ifndef x86_64}
  1829. and (
  1830. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1831. don't have an 8-bit representation }
  1832. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1833. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1834. )
  1835. {$endif x86_64}
  1836. )
  1837. )
  1838. ) then
  1839. begin
  1840. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  1841. Result := True;
  1842. end;
  1843. top_ref:
  1844. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  1845. Result := True;
  1846. else
  1847. ;
  1848. end;
  1849. end;
  1850. { Replaces all references to AOldReg in an instruction to ANewReg }
  1851. function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  1852. const
  1853. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  1854. var
  1855. OperIdx: Integer;
  1856. begin
  1857. Result := False;
  1858. for OperIdx := 0 to p.ops - 1 do
  1859. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) and
  1860. { The shift and rotate instructions can only use CL }
  1861. not (
  1862. (OperIdx = 0) and
  1863. { This second condition just helps to avoid unnecessarily
  1864. calling MatchInstruction for 10 different opcodes }
  1865. (p.oper[0]^.reg = NR_CL) and
  1866. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  1867. ) then
  1868. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  1869. end;
  1870. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean; inline;
  1871. begin
  1872. Result :=
  1873. (ref^.index = NR_NO) and
  1874. (
  1875. {$ifdef x86_64}
  1876. (
  1877. (ref^.base = NR_RIP) and
  1878. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  1879. ) or
  1880. {$endif x86_64}
  1881. (ref^.base = NR_STACK_POINTER_REG) or
  1882. (ref^.base = current_procinfo.framepointer)
  1883. );
  1884. end;
  1885. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  1886. var
  1887. l: asizeint;
  1888. begin
  1889. Result := False;
  1890. { Should have been checked previously }
  1891. if p.opcode <> A_LEA then
  1892. InternalError(2020072501);
  1893. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  1894. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  1895. not(cs_opt_size in current_settings.optimizerswitches) then
  1896. exit;
  1897. with p.oper[0]^.ref^ do
  1898. begin
  1899. if (base <> p.oper[1]^.reg) or
  1900. (index <> NR_NO) or
  1901. assigned(symbol) then
  1902. exit;
  1903. l:=offset;
  1904. if (l=1) and UseIncDec then
  1905. begin
  1906. p.opcode:=A_INC;
  1907. p.loadreg(0,p.oper[1]^.reg);
  1908. p.ops:=1;
  1909. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  1910. end
  1911. else if (l=-1) and UseIncDec then
  1912. begin
  1913. p.opcode:=A_DEC;
  1914. p.loadreg(0,p.oper[1]^.reg);
  1915. p.ops:=1;
  1916. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  1917. end
  1918. else
  1919. begin
  1920. if (l<0) and (l<>-2147483648) then
  1921. begin
  1922. p.opcode:=A_SUB;
  1923. p.loadConst(0,-l);
  1924. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  1925. end
  1926. else
  1927. begin
  1928. p.opcode:=A_ADD;
  1929. p.loadConst(0,l);
  1930. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  1931. end;
  1932. end;
  1933. end;
  1934. Result := True;
  1935. end;
  1936. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  1937. var
  1938. CurrentReg, ReplaceReg: TRegister;
  1939. begin
  1940. Result := False;
  1941. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  1942. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  1943. case hp.opcode of
  1944. A_FSTSW, A_FNSTSW,
  1945. A_IN, A_INS, A_OUT, A_OUTS,
  1946. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  1947. { These routines have explicit operands, but they are restricted in
  1948. what they can be (e.g. IN and OUT can only read from AL, AX or
  1949. EAX. }
  1950. Exit;
  1951. A_IMUL:
  1952. begin
  1953. { The 1-operand version writes to implicit registers
  1954. The 2-operand version reads from the first operator, and reads
  1955. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  1956. the 3-operand version reads from a register that it doesn't write to
  1957. }
  1958. case hp.ops of
  1959. 1:
  1960. if (
  1961. (
  1962. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  1963. ) or
  1964. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  1965. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1966. begin
  1967. Result := True;
  1968. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  1969. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1970. end;
  1971. 2:
  1972. { Only modify the first parameter }
  1973. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1974. begin
  1975. Result := True;
  1976. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  1977. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1978. end;
  1979. 3:
  1980. { Only modify the second parameter }
  1981. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  1982. begin
  1983. Result := True;
  1984. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  1985. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1986. end;
  1987. else
  1988. InternalError(2020012901);
  1989. end;
  1990. end;
  1991. else
  1992. if (hp.ops > 0) and
  1993. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  1994. begin
  1995. Result := True;
  1996. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  1997. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1998. end;
  1999. end;
  2000. end;
  2001. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2002. var
  2003. hp1, hp2, hp3: tai;
  2004. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2005. begin
  2006. if taicpu(hp1).opcode = signed_movop then
  2007. begin
  2008. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2009. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2010. end
  2011. else
  2012. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2013. end;
  2014. var
  2015. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2016. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2017. NewSize: topsize;
  2018. CurrentReg: TRegister;
  2019. begin
  2020. Result:=false;
  2021. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2022. { remove mov reg1,reg1? }
  2023. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2024. then
  2025. begin
  2026. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2027. { take care of the register (de)allocs following p }
  2028. RemoveCurrentP(p, hp1);
  2029. Result:=true;
  2030. exit;
  2031. end;
  2032. { All the next optimisations require a next instruction }
  2033. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2034. Exit;
  2035. { Look for:
  2036. mov %reg1,%reg2
  2037. ??? %reg2,r/m
  2038. Change to:
  2039. mov %reg1,%reg2
  2040. ??? %reg1,r/m
  2041. }
  2042. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2043. begin
  2044. CurrentReg := taicpu(p).oper[1]^.reg;
  2045. if RegReadByInstruction(CurrentReg, hp1) and
  2046. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2047. begin
  2048. TransferUsedRegs(TmpUsedRegs);
  2049. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2050. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2051. { Just in case something didn't get modified (e.g. an
  2052. implicit register) }
  2053. not RegReadByInstruction(CurrentReg, hp1) then
  2054. begin
  2055. { We can remove the original MOV }
  2056. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2057. RemoveCurrentp(p, hp1);
  2058. { UsedRegs got updated by RemoveCurrentp }
  2059. Result := True;
  2060. Exit;
  2061. end;
  2062. { If we know a MOV instruction has become a null operation, we might as well
  2063. get rid of it now to save time. }
  2064. if (taicpu(hp1).opcode = A_MOV) and
  2065. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2066. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2067. { Just being a register is enough to confirm it's a null operation }
  2068. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2069. begin
  2070. Result := True;
  2071. { Speed-up to reduce a pipeline stall... if we had something like...
  2072. movl %eax,%edx
  2073. movw %dx,%ax
  2074. ... the second instruction would change to movw %ax,%ax, but
  2075. given that it is now %ax that's active rather than %eax,
  2076. penalties might occur due to a partial register write, so instead,
  2077. change it to a MOVZX instruction when optimising for speed.
  2078. }
  2079. if not (cs_opt_size in current_settings.optimizerswitches) and
  2080. IsMOVZXAcceptable and
  2081. (taicpu(hp1).opsize < taicpu(p).opsize)
  2082. {$ifdef x86_64}
  2083. { operations already implicitly set the upper 64 bits to zero }
  2084. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2085. {$endif x86_64}
  2086. then
  2087. begin
  2088. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2089. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2090. case taicpu(p).opsize of
  2091. S_W:
  2092. if taicpu(hp1).opsize = S_B then
  2093. taicpu(hp1).opsize := S_BL
  2094. else
  2095. InternalError(2020012911);
  2096. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2097. case taicpu(hp1).opsize of
  2098. S_B:
  2099. taicpu(hp1).opsize := S_BL;
  2100. S_W:
  2101. taicpu(hp1).opsize := S_WL;
  2102. else
  2103. InternalError(2020012912);
  2104. end;
  2105. else
  2106. InternalError(2020012910);
  2107. end;
  2108. taicpu(hp1).opcode := A_MOVZX;
  2109. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2110. end
  2111. else
  2112. begin
  2113. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2114. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2115. RemoveInstruction(hp1);
  2116. { The instruction after what was hp1 is now the immediate next instruction,
  2117. so we can continue to make optimisations if it's present }
  2118. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2119. Exit;
  2120. hp1 := hp2;
  2121. end;
  2122. end;
  2123. end;
  2124. end;
  2125. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2126. overwrites the original destination register. e.g.
  2127. movl ###,%reg2d
  2128. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2129. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2130. }
  2131. if (taicpu(p).oper[1]^.typ = top_reg) and
  2132. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2133. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2134. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2135. begin
  2136. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2137. begin
  2138. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2139. case taicpu(p).oper[0]^.typ of
  2140. top_const:
  2141. { We have something like:
  2142. movb $x, %regb
  2143. movzbl %regb,%regd
  2144. Change to:
  2145. movl $x, %regd
  2146. }
  2147. begin
  2148. case taicpu(hp1).opsize of
  2149. S_BW:
  2150. begin
  2151. convert_mov_value(A_MOVSX, $FF);
  2152. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2153. taicpu(p).opsize := S_W;
  2154. end;
  2155. S_BL:
  2156. begin
  2157. convert_mov_value(A_MOVSX, $FF);
  2158. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2159. taicpu(p).opsize := S_L;
  2160. end;
  2161. S_WL:
  2162. begin
  2163. convert_mov_value(A_MOVSX, $FFFF);
  2164. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2165. taicpu(p).opsize := S_L;
  2166. end;
  2167. {$ifdef x86_64}
  2168. S_BQ:
  2169. begin
  2170. convert_mov_value(A_MOVSX, $FF);
  2171. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2172. taicpu(p).opsize := S_Q;
  2173. end;
  2174. S_WQ:
  2175. begin
  2176. convert_mov_value(A_MOVSX, $FFFF);
  2177. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2178. taicpu(p).opsize := S_Q;
  2179. end;
  2180. S_LQ:
  2181. begin
  2182. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2183. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2184. taicpu(p).opsize := S_Q;
  2185. end;
  2186. {$endif x86_64}
  2187. else
  2188. { If hp1 was a MOV instruction, it should have been
  2189. optimised already }
  2190. InternalError(2020021001);
  2191. end;
  2192. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2193. RemoveInstruction(hp1);
  2194. Result := True;
  2195. Exit;
  2196. end;
  2197. top_ref:
  2198. { We have something like:
  2199. movb mem, %regb
  2200. movzbl %regb,%regd
  2201. Change to:
  2202. movzbl mem, %regd
  2203. }
  2204. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2205. begin
  2206. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2207. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2208. RemoveCurrentP(p, hp1);
  2209. Result:=True;
  2210. Exit;
  2211. end;
  2212. else
  2213. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2214. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2215. Exit;
  2216. end;
  2217. end
  2218. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2219. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2220. optimised }
  2221. else
  2222. begin
  2223. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2224. RemoveCurrentP(p, hp1);
  2225. Result := True;
  2226. Exit;
  2227. end;
  2228. end;
  2229. if (taicpu(hp1).opcode = A_AND) and
  2230. (taicpu(p).oper[1]^.typ = top_reg) and
  2231. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2232. begin
  2233. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2234. begin
  2235. case taicpu(p).opsize of
  2236. S_L:
  2237. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2238. begin
  2239. { Optimize out:
  2240. mov x, %reg
  2241. and ffffffffh, %reg
  2242. }
  2243. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2244. RemoveInstruction(hp1);
  2245. Result:=true;
  2246. exit;
  2247. end;
  2248. S_Q: { TODO: Confirm if this is even possible }
  2249. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2250. begin
  2251. { Optimize out:
  2252. mov x, %reg
  2253. and ffffffffffffffffh, %reg
  2254. }
  2255. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2256. RemoveInstruction(hp1);
  2257. Result:=true;
  2258. exit;
  2259. end;
  2260. else
  2261. ;
  2262. end;
  2263. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2264. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2265. GetNextInstruction(hp1,hp2) and
  2266. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2267. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2268. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2269. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2270. GetNextInstruction(hp2,hp3) and
  2271. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2272. (taicpu(hp3).condition in [C_E,C_NE]) then
  2273. begin
  2274. TransferUsedRegs(TmpUsedRegs);
  2275. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2276. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2277. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2278. begin
  2279. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2280. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2281. taicpu(hp1).opcode:=A_TEST;
  2282. RemoveInstruction(hp2);
  2283. RemoveCurrentP(p, hp1);
  2284. Result:=true;
  2285. exit;
  2286. end;
  2287. end;
  2288. end
  2289. else if IsMOVZXAcceptable and
  2290. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2291. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2292. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2293. then
  2294. begin
  2295. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2296. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2297. case taicpu(p).opsize of
  2298. S_B:
  2299. if (taicpu(hp1).oper[0]^.val = $ff) then
  2300. begin
  2301. { Convert:
  2302. movb x, %regl movb x, %regl
  2303. andw ffh, %regw andl ffh, %regd
  2304. To:
  2305. movzbw x, %regd movzbl x, %regd
  2306. (Identical registers, just different sizes)
  2307. }
  2308. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2309. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2310. case taicpu(hp1).opsize of
  2311. S_W: NewSize := S_BW;
  2312. S_L: NewSize := S_BL;
  2313. {$ifdef x86_64}
  2314. S_Q: NewSize := S_BQ;
  2315. {$endif x86_64}
  2316. else
  2317. InternalError(2018011510);
  2318. end;
  2319. end
  2320. else
  2321. NewSize := S_NO;
  2322. S_W:
  2323. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2324. begin
  2325. { Convert:
  2326. movw x, %regw
  2327. andl ffffh, %regd
  2328. To:
  2329. movzwl x, %regd
  2330. (Identical registers, just different sizes)
  2331. }
  2332. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2333. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2334. case taicpu(hp1).opsize of
  2335. S_L: NewSize := S_WL;
  2336. {$ifdef x86_64}
  2337. S_Q: NewSize := S_WQ;
  2338. {$endif x86_64}
  2339. else
  2340. InternalError(2018011511);
  2341. end;
  2342. end
  2343. else
  2344. NewSize := S_NO;
  2345. else
  2346. NewSize := S_NO;
  2347. end;
  2348. if NewSize <> S_NO then
  2349. begin
  2350. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2351. { The actual optimization }
  2352. taicpu(p).opcode := A_MOVZX;
  2353. taicpu(p).changeopsize(NewSize);
  2354. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2355. { Safeguard if "and" is followed by a conditional command }
  2356. TransferUsedRegs(TmpUsedRegs);
  2357. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2358. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2359. begin
  2360. { At this point, the "and" command is effectively equivalent to
  2361. "test %reg,%reg". This will be handled separately by the
  2362. Peephole Optimizer. [Kit] }
  2363. DebugMsg(SPeepholeOptimization + PreMessage +
  2364. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2365. end
  2366. else
  2367. begin
  2368. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2369. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2370. RemoveInstruction(hp1);
  2371. end;
  2372. Result := True;
  2373. Exit;
  2374. end;
  2375. end;
  2376. end;
  2377. if (taicpu(hp1).opcode = A_OR) and
  2378. (taicpu(p).oper[1]^.typ = top_reg) and
  2379. MatchOperand(taicpu(p).oper[0]^, 0) and
  2380. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2381. begin
  2382. { mov 0, %reg
  2383. or ###,%reg
  2384. Change to (only if the flags are not used):
  2385. mov ###,%reg
  2386. }
  2387. TransferUsedRegs(TmpUsedRegs);
  2388. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2389. if not (RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs)) then
  2390. begin
  2391. {$ifdef x86_64}
  2392. { OR only supports 32-bit sign-extended constants for 64-bit
  2393. instructions, so compensate for this if the constant is
  2394. encoded as a value greater than or equal to 2^31 }
  2395. if (taicpu(hp1).opsize = S_Q) and
  2396. (taicpu(hp1).oper[0]^.typ = top_const) and
  2397. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2398. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2399. {$endif x86_64}
  2400. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2401. taicpu(hp1).opcode := A_MOV;
  2402. RemoveCurrentP(p, hp1);
  2403. Result := True;
  2404. Exit;
  2405. end;
  2406. end;
  2407. { Next instruction is also a MOV ? }
  2408. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2409. begin
  2410. if (taicpu(p).oper[1]^.typ = top_reg) and
  2411. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2412. begin
  2413. CurrentReg := taicpu(p).oper[1]^.reg;
  2414. TransferUsedRegs(TmpUsedRegs);
  2415. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2416. { we have
  2417. mov x, %treg
  2418. mov %treg, y
  2419. }
  2420. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2421. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2422. { we've got
  2423. mov x, %treg
  2424. mov %treg, y
  2425. with %treg is not used after }
  2426. case taicpu(p).oper[0]^.typ Of
  2427. { top_reg is covered by DeepMOVOpt }
  2428. top_const:
  2429. begin
  2430. { change
  2431. mov const, %treg
  2432. mov %treg, y
  2433. to
  2434. mov const, y
  2435. }
  2436. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2437. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2438. begin
  2439. if taicpu(hp1).oper[1]^.typ=top_reg then
  2440. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2441. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2442. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2443. RemoveInstruction(hp1);
  2444. Result:=true;
  2445. Exit;
  2446. end;
  2447. end;
  2448. top_ref:
  2449. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2450. begin
  2451. { change
  2452. mov mem, %treg
  2453. mov %treg, %reg
  2454. to
  2455. mov mem, %reg"
  2456. }
  2457. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2458. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2459. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2460. RemoveInstruction(hp1);
  2461. Result:=true;
  2462. Exit;
  2463. end;
  2464. else
  2465. ;
  2466. end
  2467. else
  2468. { %treg is used afterwards, but all eventualities
  2469. other than the first MOV instruction being a constant
  2470. are covered by DeepMOVOpt, so only check for that }
  2471. if (taicpu(p).oper[0]^.typ = top_const) and
  2472. (
  2473. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2474. not (cs_opt_size in current_settings.optimizerswitches) or
  2475. (taicpu(hp1).opsize = S_B)
  2476. ) and
  2477. (
  2478. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2479. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2480. ) then
  2481. begin
  2482. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2483. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2484. end;
  2485. end;
  2486. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2487. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2488. { mov reg1, mem1 or mov mem1, reg1
  2489. mov mem2, reg2 mov reg2, mem2}
  2490. begin
  2491. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2492. { mov reg1, mem1 or mov mem1, reg1
  2493. mov mem2, reg1 mov reg2, mem1}
  2494. begin
  2495. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2496. { Removes the second statement from
  2497. mov reg1, mem1/reg2
  2498. mov mem1/reg2, reg1 }
  2499. begin
  2500. if taicpu(p).oper[0]^.typ=top_reg then
  2501. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2502. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2503. RemoveInstruction(hp1);
  2504. Result:=true;
  2505. exit;
  2506. end
  2507. else
  2508. begin
  2509. TransferUsedRegs(TmpUsedRegs);
  2510. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2511. if (taicpu(p).oper[1]^.typ = top_ref) and
  2512. { mov reg1, mem1
  2513. mov mem2, reg1 }
  2514. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2515. GetNextInstruction(hp1, hp2) and
  2516. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2517. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2518. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2519. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2520. { change to
  2521. mov reg1, mem1 mov reg1, mem1
  2522. mov mem2, reg1 cmp reg1, mem2
  2523. cmp mem1, reg1
  2524. }
  2525. begin
  2526. RemoveInstruction(hp2);
  2527. taicpu(hp1).opcode := A_CMP;
  2528. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2529. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2530. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2531. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2532. end;
  2533. end;
  2534. end
  2535. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2536. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2537. begin
  2538. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2539. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2540. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2541. end
  2542. else
  2543. begin
  2544. TransferUsedRegs(TmpUsedRegs);
  2545. if GetNextInstruction(hp1, hp2) and
  2546. MatchOpType(taicpu(p),top_ref,top_reg) and
  2547. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2548. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2549. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2550. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2551. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2552. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2553. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2554. { mov mem1, %reg1
  2555. mov %reg1, mem2
  2556. mov mem2, reg2
  2557. to:
  2558. mov mem1, reg2
  2559. mov reg2, mem2}
  2560. begin
  2561. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2562. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2563. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2564. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2565. RemoveInstruction(hp2);
  2566. end
  2567. {$ifdef i386}
  2568. { this is enabled for i386 only, as the rules to create the reg sets below
  2569. are too complicated for x86-64, so this makes this code too error prone
  2570. on x86-64
  2571. }
  2572. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2573. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2574. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2575. { mov mem1, reg1 mov mem1, reg1
  2576. mov reg1, mem2 mov reg1, mem2
  2577. mov mem2, reg2 mov mem2, reg1
  2578. to: to:
  2579. mov mem1, reg1 mov mem1, reg1
  2580. mov mem1, reg2 mov reg1, mem2
  2581. mov reg1, mem2
  2582. or (if mem1 depends on reg1
  2583. and/or if mem2 depends on reg2)
  2584. to:
  2585. mov mem1, reg1
  2586. mov reg1, mem2
  2587. mov reg1, reg2
  2588. }
  2589. begin
  2590. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  2591. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  2592. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  2593. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  2594. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2595. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  2596. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2597. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  2598. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  2599. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2600. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  2601. end
  2602. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  2603. begin
  2604. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  2605. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2606. end
  2607. else
  2608. begin
  2609. RemoveInstruction(hp2);
  2610. end
  2611. {$endif i386}
  2612. ;
  2613. end;
  2614. end
  2615. { movl [mem1],reg1
  2616. movl [mem1],reg2
  2617. to
  2618. movl [mem1],reg1
  2619. movl reg1,reg2
  2620. }
  2621. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  2622. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2623. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2624. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2625. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2626. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2627. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2628. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2629. begin
  2630. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2631. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2632. end;
  2633. { movl const1,[mem1]
  2634. movl [mem1],reg1
  2635. to
  2636. movl const1,reg1
  2637. movl reg1,[mem1]
  2638. }
  2639. if MatchOpType(Taicpu(p),top_const,top_ref) and
  2640. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  2641. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2642. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  2643. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  2644. begin
  2645. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2646. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  2647. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  2648. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  2649. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  2650. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  2651. Result:=true;
  2652. exit;
  2653. end;
  2654. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  2655. end;
  2656. { search further than the next instruction for a mov }
  2657. if
  2658. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  2659. (taicpu(p).oper[1]^.typ = top_reg) and
  2660. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  2661. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  2662. begin
  2663. { we work with hp2 here, so hp1 can be still used later on when
  2664. checking for GetNextInstruction_p }
  2665. hp3 := hp1;
  2666. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  2667. CrossJump := False;
  2668. while GetNextInstructionUsingRegCond(hp3,hp2,taicpu(p).oper[1]^.reg,CrossJump) and
  2669. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  2670. (hp2.typ=ait_instruction) do
  2671. begin
  2672. case taicpu(hp2).opcode of
  2673. A_MOV:
  2674. if MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^.reg) and
  2675. ((taicpu(p).oper[0]^.typ=top_const) or
  2676. ((taicpu(p).oper[0]^.typ=top_reg) and
  2677. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  2678. )
  2679. ) then
  2680. begin
  2681. { we have
  2682. mov x, %treg
  2683. mov %treg, y
  2684. }
  2685. TransferUsedRegs(TmpUsedRegs);
  2686. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2687. { We don't need to call UpdateUsedRegs for every instruction between
  2688. p and hp2 because the register we're concerned about will not
  2689. become deallocated (otherwise GetNextInstructionUsingReg would
  2690. have stopped at an earlier instruction). [Kit] }
  2691. TempRegUsed :=
  2692. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  2693. RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) or
  2694. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1);
  2695. case taicpu(p).oper[0]^.typ Of
  2696. top_reg:
  2697. begin
  2698. { change
  2699. mov %reg, %treg
  2700. mov %treg, y
  2701. to
  2702. mov %reg, y
  2703. }
  2704. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  2705. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2706. if taicpu(hp2).oper[1]^.reg = CurrentReg then
  2707. begin
  2708. { %reg = y - remove hp2 completely (doing it here instead of relying on
  2709. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  2710. if TempRegUsed then
  2711. begin
  2712. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  2713. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2714. { Set the start of the next GetNextInstructionUsingRegCond search
  2715. to start at the entry right before hp2 (which is about to be removed) }
  2716. hp3 := tai(hp2.Previous);
  2717. RemoveInstruction(hp2);
  2718. { See if there's more we can optimise }
  2719. Continue;
  2720. end
  2721. else
  2722. begin
  2723. RemoveInstruction(hp2);
  2724. { We can remove the original MOV too }
  2725. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  2726. RemoveCurrentP(p, hp1);
  2727. Result:=true;
  2728. Exit;
  2729. end;
  2730. end
  2731. else
  2732. begin
  2733. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2734. taicpu(hp2).loadReg(0, CurrentReg);
  2735. if TempRegUsed then
  2736. begin
  2737. { Don't remove the first instruction if the temporary register is in use }
  2738. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  2739. { No need to set Result to True. If there's another instruction later on
  2740. that can be optimised, it will be detected when the main Pass 1 loop
  2741. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2742. end
  2743. else
  2744. begin
  2745. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  2746. RemoveCurrentP(p, hp1);
  2747. Result:=true;
  2748. Exit;
  2749. end;
  2750. end;
  2751. end;
  2752. top_const:
  2753. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  2754. begin
  2755. { change
  2756. mov const, %treg
  2757. mov %treg, y
  2758. to
  2759. mov const, y
  2760. }
  2761. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  2762. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2763. begin
  2764. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2765. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  2766. if TempRegUsed then
  2767. begin
  2768. { Don't remove the first instruction if the temporary register is in use }
  2769. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  2770. { No need to set Result to True. If there's another instruction later on
  2771. that can be optimised, it will be detected when the main Pass 1 loop
  2772. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2773. end
  2774. else
  2775. begin
  2776. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  2777. RemoveCurrentP(p, hp1);
  2778. Result:=true;
  2779. Exit;
  2780. end;
  2781. end;
  2782. end;
  2783. else
  2784. Internalerror(2019103001);
  2785. end;
  2786. end;
  2787. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  2788. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  2789. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  2790. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2791. begin
  2792. {
  2793. Change from:
  2794. mov ###, %reg
  2795. ...
  2796. movs/z %reg,%reg (Same register, just different sizes)
  2797. To:
  2798. movs/z ###, %reg (Longer version)
  2799. ...
  2800. (remove)
  2801. }
  2802. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  2803. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  2804. { Keep the first instruction as mov if ### is a constant }
  2805. if taicpu(p).oper[0]^.typ = top_const then
  2806. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  2807. else
  2808. begin
  2809. taicpu(p).opcode := taicpu(hp2).opcode;
  2810. taicpu(p).opsize := taicpu(hp2).opsize;
  2811. end;
  2812. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  2813. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  2814. RemoveInstruction(hp2);
  2815. Result := True;
  2816. Exit;
  2817. end;
  2818. else
  2819. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2820. begin
  2821. CurrentReg := taicpu(p).oper[1]^.reg;
  2822. TransferUsedRegs(TmpUsedRegs);
  2823. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2824. if
  2825. not RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) and
  2826. not RegModifiedBetween(taicpu(p).oper[0]^.reg, hp1, hp2) and
  2827. DeepMovOpt(taicpu(p), taicpu(hp2)) then
  2828. begin
  2829. { Just in case something didn't get modified (e.g. an
  2830. implicit register) }
  2831. if not RegReadByInstruction(CurrentReg, hp2) and
  2832. { If a conditional jump was crossed, do not delete
  2833. the original MOV no matter what }
  2834. not CrossJump then
  2835. begin
  2836. TransferUsedRegs(TmpUsedRegs);
  2837. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2838. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2839. if
  2840. { Make sure the original register isn't still present
  2841. and has been written to (e.g. with SHRX) }
  2842. RegLoadedWithNewValue(CurrentReg, hp2) or
  2843. not RegUsedAfterInstruction(CurrentReg, hp2, TmpUsedRegs) then
  2844. begin
  2845. { We can remove the original MOV }
  2846. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  2847. RemoveCurrentp(p, hp1);
  2848. Result := True;
  2849. Exit;
  2850. end
  2851. else
  2852. begin
  2853. { See if there's more we can optimise }
  2854. hp3 := hp2;
  2855. Continue;
  2856. end;
  2857. end;
  2858. end;
  2859. end;
  2860. end;
  2861. { Break out of the while loop under normal circumstances }
  2862. Break;
  2863. end;
  2864. end;
  2865. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  2866. (taicpu(p).oper[1]^.typ = top_reg) and
  2867. (taicpu(p).opsize = S_L) and
  2868. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  2869. (taicpu(hp2).opcode = A_AND) and
  2870. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  2871. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2872. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  2873. ) then
  2874. begin
  2875. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  2876. begin
  2877. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  2878. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  2879. begin
  2880. { Optimize out:
  2881. mov x, %reg
  2882. and ffffffffh, %reg
  2883. }
  2884. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  2885. RemoveInstruction(hp2);
  2886. Result:=true;
  2887. exit;
  2888. end;
  2889. end;
  2890. end;
  2891. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  2892. x >= RetOffset) as it doesn't do anything (it writes either to a
  2893. parameter or to the temporary storage room for the function
  2894. result)
  2895. }
  2896. if IsExitCode(hp1) and
  2897. (taicpu(p).oper[1]^.typ = top_ref) and
  2898. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  2899. (
  2900. (
  2901. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  2902. not (
  2903. assigned(current_procinfo.procdef.funcretsym) and
  2904. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  2905. )
  2906. ) or
  2907. { Also discard writes to the stack that are below the base pointer,
  2908. as this is temporary storage rather than a function result on the
  2909. stack, say. }
  2910. (
  2911. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  2912. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  2913. )
  2914. ) then
  2915. begin
  2916. RemoveCurrentp(p, hp1);
  2917. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  2918. RemoveLastDeallocForFuncRes(p);
  2919. Result:=true;
  2920. exit;
  2921. end;
  2922. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  2923. begin
  2924. if MatchOpType(taicpu(p),top_reg,top_ref) and
  2925. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2926. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2927. begin
  2928. { change
  2929. mov reg1, mem1
  2930. test/cmp x, mem1
  2931. to
  2932. mov reg1, mem1
  2933. test/cmp x, reg1
  2934. }
  2935. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  2936. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  2937. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2938. Result := True;
  2939. Exit;
  2940. end;
  2941. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2942. { The x86 assemblers have difficulty comparing values against absolute addresses }
  2943. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  2944. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  2945. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  2946. (
  2947. (
  2948. (taicpu(hp1).opcode = A_TEST)
  2949. ) or (
  2950. (taicpu(hp1).opcode = A_CMP) and
  2951. { A sanity check more than anything }
  2952. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  2953. )
  2954. ) then
  2955. begin
  2956. { change
  2957. mov mem, %reg
  2958. cmp/test x, %reg / test %reg,%reg
  2959. (reg deallocated)
  2960. to
  2961. cmp/test x, mem / cmp 0, mem
  2962. }
  2963. TransferUsedRegs(TmpUsedRegs);
  2964. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2965. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2966. begin
  2967. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  2968. if (taicpu(hp1).opcode = A_TEST) and
  2969. (
  2970. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  2971. MatchOperand(taicpu(hp1).oper[0]^, -1)
  2972. ) then
  2973. begin
  2974. taicpu(hp1).opcode := A_CMP;
  2975. taicpu(hp1).loadconst(0, 0);
  2976. end;
  2977. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  2978. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  2979. RemoveCurrentP(p, hp1);
  2980. Result := True;
  2981. Exit;
  2982. end;
  2983. end;
  2984. end;
  2985. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  2986. { If the flags register is in use, don't change the instruction to an
  2987. ADD otherwise this will scramble the flags. [Kit] }
  2988. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  2989. begin
  2990. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  2991. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  2992. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  2993. ) or
  2994. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  2995. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  2996. )
  2997. ) then
  2998. { mov reg1,ref
  2999. lea reg2,[reg1,reg2]
  3000. to
  3001. add reg2,ref}
  3002. begin
  3003. TransferUsedRegs(TmpUsedRegs);
  3004. { reg1 may not be used afterwards }
  3005. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3006. begin
  3007. Taicpu(hp1).opcode:=A_ADD;
  3008. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3009. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3010. RemoveCurrentp(p, hp1);
  3011. result:=true;
  3012. exit;
  3013. end;
  3014. end;
  3015. { If the LEA instruction can be converted into an arithmetic instruction,
  3016. it may be possible to then fold it in the next optimisation, otherwise
  3017. there's nothing more that can be optimised here. }
  3018. if not ConvertLEA(taicpu(hp1)) then
  3019. Exit;
  3020. end;
  3021. if (taicpu(p).oper[1]^.typ = top_reg) and
  3022. (hp1.typ = ait_instruction) and
  3023. GetNextInstruction(hp1, hp2) and
  3024. MatchInstruction(hp2,A_MOV,[]) and
  3025. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3026. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3027. (
  3028. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3029. {$ifdef x86_64}
  3030. or
  3031. (
  3032. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3033. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3034. )
  3035. {$endif x86_64}
  3036. ) then
  3037. begin
  3038. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3039. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3040. { change movsX/movzX reg/ref, reg2
  3041. add/sub/or/... reg3/$const, reg2
  3042. mov reg2 reg/ref
  3043. dealloc reg2
  3044. to
  3045. add/sub/or/... reg3/$const, reg/ref }
  3046. begin
  3047. TransferUsedRegs(TmpUsedRegs);
  3048. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3049. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3050. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3051. begin
  3052. { by example:
  3053. movswl %si,%eax movswl %si,%eax p
  3054. decl %eax addl %edx,%eax hp1
  3055. movw %ax,%si movw %ax,%si hp2
  3056. ->
  3057. movswl %si,%eax movswl %si,%eax p
  3058. decw %eax addw %edx,%eax hp1
  3059. movw %ax,%si movw %ax,%si hp2
  3060. }
  3061. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3062. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3063. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3064. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3065. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3066. {
  3067. ->
  3068. movswl %si,%eax movswl %si,%eax p
  3069. decw %si addw %dx,%si hp1
  3070. movw %ax,%si movw %ax,%si hp2
  3071. }
  3072. case taicpu(hp1).ops of
  3073. 1:
  3074. begin
  3075. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3076. if taicpu(hp1).oper[0]^.typ=top_reg then
  3077. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3078. end;
  3079. 2:
  3080. begin
  3081. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3082. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3083. (taicpu(hp1).opcode<>A_SHL) and
  3084. (taicpu(hp1).opcode<>A_SHR) and
  3085. (taicpu(hp1).opcode<>A_SAR) then
  3086. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3087. end;
  3088. else
  3089. internalerror(2008042701);
  3090. end;
  3091. {
  3092. ->
  3093. decw %si addw %dx,%si p
  3094. }
  3095. RemoveInstruction(hp2);
  3096. RemoveCurrentP(p, hp1);
  3097. Result:=True;
  3098. Exit;
  3099. end;
  3100. end;
  3101. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3102. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3103. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3104. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3105. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3106. )
  3107. {$ifdef i386}
  3108. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3109. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3110. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3111. {$endif i386}
  3112. then
  3113. { change movsX/movzX reg/ref, reg2
  3114. add/sub/or/... regX/$const, reg2
  3115. mov reg2, reg3
  3116. dealloc reg2
  3117. to
  3118. movsX/movzX reg/ref, reg3
  3119. add/sub/or/... reg3/$const, reg3
  3120. }
  3121. begin
  3122. TransferUsedRegs(TmpUsedRegs);
  3123. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3124. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3125. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3126. begin
  3127. { by example:
  3128. movswl %si,%eax movswl %si,%eax p
  3129. decl %eax addl %edx,%eax hp1
  3130. movw %ax,%si movw %ax,%si hp2
  3131. ->
  3132. movswl %si,%eax movswl %si,%eax p
  3133. decw %eax addw %edx,%eax hp1
  3134. movw %ax,%si movw %ax,%si hp2
  3135. }
  3136. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3137. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3138. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3139. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3140. { limit size of constants as well to avoid assembler errors, but
  3141. check opsize to avoid overflow when left shifting the 1 }
  3142. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3143. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3144. {$ifdef x86_64}
  3145. { Be careful of, for example:
  3146. movl %reg1,%reg2
  3147. addl %reg3,%reg2
  3148. movq %reg2,%reg4
  3149. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3150. }
  3151. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3152. begin
  3153. taicpu(hp2).changeopsize(S_L);
  3154. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3155. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3156. end;
  3157. {$endif x86_64}
  3158. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3159. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3160. if taicpu(p).oper[0]^.typ=top_reg then
  3161. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3162. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3163. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3164. {
  3165. ->
  3166. movswl %si,%eax movswl %si,%eax p
  3167. decw %si addw %dx,%si hp1
  3168. movw %ax,%si movw %ax,%si hp2
  3169. }
  3170. case taicpu(hp1).ops of
  3171. 1:
  3172. begin
  3173. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3174. if taicpu(hp1).oper[0]^.typ=top_reg then
  3175. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3176. end;
  3177. 2:
  3178. begin
  3179. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3180. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3181. (taicpu(hp1).opcode<>A_SHL) and
  3182. (taicpu(hp1).opcode<>A_SHR) and
  3183. (taicpu(hp1).opcode<>A_SAR) then
  3184. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3185. end;
  3186. else
  3187. internalerror(2018111801);
  3188. end;
  3189. {
  3190. ->
  3191. decw %si addw %dx,%si p
  3192. }
  3193. RemoveInstruction(hp2);
  3194. end;
  3195. end;
  3196. end;
  3197. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3198. GetNextInstruction(hp1, hp2) and
  3199. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3200. MatchOperand(Taicpu(p).oper[0]^,0) and
  3201. (Taicpu(p).oper[1]^.typ = top_reg) and
  3202. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3203. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3204. { mov reg1,0
  3205. bts reg1,operand1 --> mov reg1,operand2
  3206. or reg1,operand2 bts reg1,operand1}
  3207. begin
  3208. Taicpu(hp2).opcode:=A_MOV;
  3209. asml.remove(hp1);
  3210. insertllitem(hp2,hp2.next,hp1);
  3211. RemoveCurrentp(p, hp1);
  3212. Result:=true;
  3213. exit;
  3214. end;
  3215. {$ifdef x86_64}
  3216. { Convert:
  3217. movq x(ref),%reg64
  3218. shrq y,%reg64
  3219. To:
  3220. movq x+4(ref),%reg32
  3221. shrq y-32,%reg32 (Remove if y = 32)
  3222. }
  3223. if (taicpu(p).opsize = S_Q) and
  3224. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3225. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3226. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3227. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3228. (taicpu(hp1).oper[0]^.val >= 32) and
  3229. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3230. begin
  3231. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3232. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3233. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3234. { Convert to 32-bit }
  3235. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3236. taicpu(p).opsize := S_L;
  3237. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3238. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3239. if (taicpu(hp1).oper[0]^.val = 32) then
  3240. begin
  3241. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3242. RemoveInstruction(hp1);
  3243. end
  3244. else
  3245. begin
  3246. { This will potentially open up more arithmetic operations since
  3247. the peephole optimizer now has a big hint that only the lower
  3248. 32 bits are currently in use (and opcodes are smaller in size) }
  3249. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3250. taicpu(hp1).opsize := S_L;
  3251. Dec(taicpu(hp1).oper[0]^.val, 32);
  3252. DebugMsg(SPeepholeOptimization + PreMessage +
  3253. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3254. end;
  3255. Result := True;
  3256. Exit;
  3257. end;
  3258. {$endif x86_64}
  3259. end;
  3260. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3261. var
  3262. hp1 : tai;
  3263. begin
  3264. Result:=false;
  3265. if taicpu(p).ops <> 2 then
  3266. exit;
  3267. if GetNextInstruction(p,hp1) and
  3268. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3269. (taicpu(hp1).ops = 2) then
  3270. begin
  3271. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3272. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3273. { movXX reg1, mem1 or movXX mem1, reg1
  3274. movXX mem2, reg2 movXX reg2, mem2}
  3275. begin
  3276. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3277. { movXX reg1, mem1 or movXX mem1, reg1
  3278. movXX mem2, reg1 movXX reg2, mem1}
  3279. begin
  3280. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3281. begin
  3282. { Removes the second statement from
  3283. movXX reg1, mem1/reg2
  3284. movXX mem1/reg2, reg1
  3285. }
  3286. if taicpu(p).oper[0]^.typ=top_reg then
  3287. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3288. { Removes the second statement from
  3289. movXX mem1/reg1, reg2
  3290. movXX reg2, mem1/reg1
  3291. }
  3292. if (taicpu(p).oper[1]^.typ=top_reg) and
  3293. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3294. begin
  3295. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3296. RemoveInstruction(hp1);
  3297. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3298. end
  3299. else
  3300. begin
  3301. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3302. RemoveInstruction(hp1);
  3303. end;
  3304. Result:=true;
  3305. exit;
  3306. end
  3307. end;
  3308. end;
  3309. end;
  3310. end;
  3311. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3312. var
  3313. hp1 : tai;
  3314. begin
  3315. result:=false;
  3316. { replace
  3317. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3318. MovX %mreg2,%mreg1
  3319. dealloc %mreg2
  3320. by
  3321. <Op>X %mreg2,%mreg1
  3322. ?
  3323. }
  3324. if GetNextInstruction(p,hp1) and
  3325. { we mix single and double opperations here because we assume that the compiler
  3326. generates vmovapd only after double operations and vmovaps only after single operations }
  3327. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3328. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3329. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3330. (taicpu(p).oper[0]^.typ=top_reg) then
  3331. begin
  3332. TransferUsedRegs(TmpUsedRegs);
  3333. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3334. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3335. begin
  3336. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3337. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3338. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3339. RemoveInstruction(hp1);
  3340. result:=true;
  3341. end;
  3342. end;
  3343. end;
  3344. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3345. var
  3346. hp1, p_label, p_dist, hp1_dist: tai;
  3347. JumpLabel, JumpLabel_dist: TAsmLabel;
  3348. begin
  3349. Result := False;
  3350. if (taicpu(p).oper[1]^.typ = top_reg) then
  3351. begin
  3352. if GetNextInstruction(p, hp1) and
  3353. MatchInstruction(hp1,A_MOV,[]) and
  3354. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  3355. (
  3356. (taicpu(p).oper[0]^.typ <> top_reg) or
  3357. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  3358. ) then
  3359. begin
  3360. { If we have something like:
  3361. test %reg1,%reg1
  3362. mov 0,%reg2
  3363. And no registers are shared (the two %reg1's can be different, as
  3364. long as neither of them are also %reg2), move the MOV command to
  3365. before the comparison as this means it can be optimised without
  3366. worrying about the FLAGS register. (This combination is generated
  3367. by "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  3368. }
  3369. SwapMovCmp(p, hp1);
  3370. Result := True;
  3371. Exit;
  3372. end;
  3373. { Search for:
  3374. test %reg,%reg
  3375. j(c1) @lbl1
  3376. ...
  3377. @lbl:
  3378. test %reg,%reg (same register)
  3379. j(c2) @lbl2
  3380. If c2 is a subset of c1, change to:
  3381. test %reg,%reg
  3382. j(c1) @lbl2
  3383. (@lbl1 may become a dead label as a result)
  3384. }
  3385. if (taicpu(p).oper[0]^.typ = top_reg) and
  3386. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  3387. MatchInstruction(hp1, A_JCC, []) and
  3388. IsJumpToLabel(taicpu(hp1)) then
  3389. begin
  3390. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  3391. p_label := nil;
  3392. if Assigned(JumpLabel) then
  3393. p_label := getlabelwithsym(JumpLabel);
  3394. if Assigned(p_label) and
  3395. GetNextInstruction(p_label, p_dist) and
  3396. MatchInstruction(p_dist, A_TEST, []) and
  3397. { It's fine if the second test uses smaller sub-registers }
  3398. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  3399. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  3400. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  3401. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  3402. GetNextInstruction(p_dist, hp1_dist) and
  3403. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  3404. begin
  3405. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  3406. if JumpLabel = JumpLabel_dist then
  3407. { This is an infinite loop }
  3408. Exit;
  3409. { Best optimisation when the first condition is a subset (or equal) of the second }
  3410. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  3411. begin
  3412. { Any registers used here will already be allocated }
  3413. if Assigned(JumpLabel_dist) then
  3414. JumpLabel_dist.IncRefs;
  3415. if Assigned(JumpLabel) then
  3416. JumpLabel.DecRefs;
  3417. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  3418. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  3419. Result := True;
  3420. Exit;
  3421. end;
  3422. end;
  3423. end;
  3424. end;
  3425. end;
  3426. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  3427. var
  3428. hp1 : tai;
  3429. begin
  3430. result:=false;
  3431. { replace
  3432. addX const,%reg1
  3433. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  3434. dealloc %reg1
  3435. by
  3436. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  3437. }
  3438. if MatchOpType(taicpu(p),top_const,top_reg) and
  3439. GetNextInstruction(p,hp1) and
  3440. MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3441. ((taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base) or
  3442. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index)) then
  3443. begin
  3444. TransferUsedRegs(TmpUsedRegs);
  3445. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3446. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3447. begin
  3448. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  3449. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base then
  3450. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  3451. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index then
  3452. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3453. RemoveCurrentP(p);
  3454. result:=true;
  3455. end;
  3456. end;
  3457. end;
  3458. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  3459. var
  3460. hp1: tai;
  3461. ref: Integer;
  3462. saveref: treference;
  3463. TempReg: TRegister;
  3464. Multiple: TCGInt;
  3465. begin
  3466. Result:=false;
  3467. { removes seg register prefixes from LEA operations, as they
  3468. don't do anything}
  3469. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  3470. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  3471. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3472. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  3473. (
  3474. { do not mess with leas accessing the stack pointer
  3475. unless it's a null operation }
  3476. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  3477. (
  3478. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  3479. (taicpu(p).oper[0]^.ref^.offset = 0)
  3480. )
  3481. ) and
  3482. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  3483. begin
  3484. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  3485. begin
  3486. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  3487. begin
  3488. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  3489. taicpu(p).oper[1]^.reg);
  3490. InsertLLItem(p.previous,p.next, hp1);
  3491. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  3492. p.free;
  3493. p:=hp1;
  3494. end
  3495. else
  3496. begin
  3497. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  3498. RemoveCurrentP(p);
  3499. end;
  3500. Result:=true;
  3501. exit;
  3502. end
  3503. else if (
  3504. { continue to use lea to adjust the stack pointer,
  3505. it is the recommended way, but only if not optimizing for size }
  3506. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  3507. (cs_opt_size in current_settings.optimizerswitches)
  3508. ) and
  3509. { If the flags register is in use, don't change the instruction
  3510. to an ADD otherwise this will scramble the flags. [Kit] }
  3511. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  3512. ConvertLEA(taicpu(p)) then
  3513. begin
  3514. Result:=true;
  3515. exit;
  3516. end;
  3517. end;
  3518. if GetNextInstruction(p,hp1) and
  3519. (hp1.typ=ait_instruction) then
  3520. begin
  3521. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  3522. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3523. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  3524. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  3525. begin
  3526. TransferUsedRegs(TmpUsedRegs);
  3527. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3528. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3529. begin
  3530. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3531. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  3532. RemoveInstruction(hp1);
  3533. result:=true;
  3534. exit;
  3535. end;
  3536. end;
  3537. { changes
  3538. lea <ref1>, reg1
  3539. <op> ...,<ref. with reg1>,...
  3540. to
  3541. <op> ...,<ref1>,... }
  3542. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  3543. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  3544. not(MatchInstruction(hp1,A_LEA,[])) then
  3545. begin
  3546. { find a reference which uses reg1 }
  3547. 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
  3548. ref:=0
  3549. 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
  3550. ref:=1
  3551. else
  3552. ref:=-1;
  3553. if (ref<>-1) and
  3554. { reg1 must be either the base or the index }
  3555. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  3556. begin
  3557. { reg1 can be removed from the reference }
  3558. saveref:=taicpu(hp1).oper[ref]^.ref^;
  3559. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  3560. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  3561. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  3562. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  3563. else
  3564. Internalerror(2019111201);
  3565. { check if the can insert all data of the lea into the second instruction }
  3566. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3567. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  3568. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  3569. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  3570. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  3571. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3572. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  3573. {$ifdef x86_64}
  3574. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  3575. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  3576. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  3577. )
  3578. {$endif x86_64}
  3579. then
  3580. begin
  3581. { reg1 might not used by the second instruction after it is remove from the reference }
  3582. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  3583. begin
  3584. TransferUsedRegs(TmpUsedRegs);
  3585. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3586. { reg1 is not updated so it might not be used afterwards }
  3587. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3588. begin
  3589. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  3590. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  3591. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3592. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3593. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3594. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  3595. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  3596. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  3597. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  3598. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  3599. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3600. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3601. RemoveCurrentP(p, hp1);
  3602. result:=true;
  3603. exit;
  3604. end
  3605. end;
  3606. end;
  3607. { recover }
  3608. taicpu(hp1).oper[ref]^.ref^:=saveref;
  3609. end;
  3610. end;
  3611. end;
  3612. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  3613. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  3614. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  3615. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  3616. begin
  3617. { Check common LEA/LEA conditions }
  3618. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3619. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  3620. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  3621. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  3622. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  3623. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  3624. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  3625. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  3626. (
  3627. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  3628. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  3629. ) and (
  3630. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  3631. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3632. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  3633. ) then
  3634. begin
  3635. { changes
  3636. lea (regX,scale), reg1
  3637. lea offset(reg1,reg1), reg1
  3638. to
  3639. lea offset(regX,scale*2), reg1
  3640. and
  3641. lea (regX,scale1), reg1
  3642. lea offset(reg1,scale2), reg1
  3643. to
  3644. lea offset(regX,scale1*scale2), reg1
  3645. ... so long as the final scale does not exceed 8
  3646. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  3647. }
  3648. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  3649. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3650. (
  3651. (
  3652. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  3653. ) or (
  3654. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3655. (
  3656. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  3657. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  3658. )
  3659. )
  3660. ) and (
  3661. (
  3662. { lea (reg1,scale2), reg1 variant }
  3663. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  3664. (
  3665. (
  3666. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  3667. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  3668. ) or (
  3669. { lea (regX,regX), reg1 variant }
  3670. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3671. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  3672. )
  3673. )
  3674. ) or (
  3675. { lea (reg1,reg1), reg1 variant }
  3676. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  3677. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  3678. )
  3679. ) then
  3680. begin
  3681. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  3682. { Make everything homogeneous to make calculations easier }
  3683. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  3684. begin
  3685. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  3686. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  3687. taicpu(p).oper[0]^.ref^.scalefactor := 2
  3688. else
  3689. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  3690. taicpu(p).oper[0]^.ref^.base := NR_NO;
  3691. end;
  3692. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  3693. begin
  3694. { Just to prevent miscalculations }
  3695. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  3696. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  3697. else
  3698. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  3699. end
  3700. else
  3701. begin
  3702. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  3703. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  3704. end;
  3705. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  3706. RemoveCurrentP(p);
  3707. result:=true;
  3708. exit;
  3709. end
  3710. { changes
  3711. lea offset1(regX), reg1
  3712. lea offset2(reg1), reg1
  3713. to
  3714. lea offset1+offset2(regX), reg1 }
  3715. else if
  3716. (
  3717. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3718. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  3719. ) or (
  3720. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  3721. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  3722. (
  3723. (
  3724. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3725. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  3726. ) or (
  3727. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3728. (
  3729. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3730. (
  3731. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3732. (
  3733. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  3734. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  3735. )
  3736. )
  3737. )
  3738. )
  3739. )
  3740. ) then
  3741. begin
  3742. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  3743. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  3744. begin
  3745. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  3746. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3747. { if the register is used as index and base, we have to increase for base as well
  3748. and adapt base }
  3749. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  3750. begin
  3751. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3752. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3753. end;
  3754. end
  3755. else
  3756. begin
  3757. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3758. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3759. end;
  3760. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3761. begin
  3762. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  3763. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3764. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3765. end;
  3766. RemoveCurrentP(p);
  3767. result:=true;
  3768. exit;
  3769. end;
  3770. end;
  3771. { Change:
  3772. leal/q $x(%reg1),%reg2
  3773. ...
  3774. shll/q $y,%reg2
  3775. To:
  3776. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  3777. }
  3778. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  3779. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3780. (taicpu(hp1).oper[0]^.val <= 3) then
  3781. begin
  3782. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  3783. TransferUsedRegs(TmpUsedRegs);
  3784. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3785. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  3786. if
  3787. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  3788. (this works even if scalefactor is zero) }
  3789. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  3790. { Ensure offset doesn't go out of bounds }
  3791. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  3792. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  3793. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  3794. (
  3795. (
  3796. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  3797. (
  3798. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3799. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  3800. (
  3801. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  3802. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3803. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  3804. )
  3805. )
  3806. ) or (
  3807. (
  3808. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  3809. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  3810. ) and
  3811. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  3812. )
  3813. ) then
  3814. begin
  3815. repeat
  3816. with taicpu(p).oper[0]^.ref^ do
  3817. begin
  3818. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  3819. if index = base then
  3820. begin
  3821. if Multiple > 4 then
  3822. { Optimisation will no longer work because resultant
  3823. scale factor will exceed 8 }
  3824. Break;
  3825. base := NR_NO;
  3826. scalefactor := 2;
  3827. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  3828. end
  3829. else if (base <> NR_NO) and (base <> NR_INVALID) then
  3830. begin
  3831. { Scale factor only works on the index register }
  3832. index := base;
  3833. base := NR_NO;
  3834. end;
  3835. { For safety }
  3836. if scalefactor <= 1 then
  3837. begin
  3838. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  3839. scalefactor := Multiple;
  3840. end
  3841. else
  3842. begin
  3843. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  3844. scalefactor := scalefactor * Multiple;
  3845. end;
  3846. offset := offset * Multiple;
  3847. end;
  3848. RemoveInstruction(hp1);
  3849. Result := True;
  3850. Exit;
  3851. { This repeat..until loop exists for the benefit of Break }
  3852. until True;
  3853. end;
  3854. end;
  3855. end;
  3856. end;
  3857. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  3858. var
  3859. hp1 : tai;
  3860. begin
  3861. DoSubAddOpt := False;
  3862. if GetLastInstruction(p, hp1) and
  3863. (hp1.typ = ait_instruction) and
  3864. (taicpu(hp1).opsize = taicpu(p).opsize) then
  3865. case taicpu(hp1).opcode Of
  3866. A_DEC:
  3867. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  3868. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3869. begin
  3870. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  3871. RemoveInstruction(hp1);
  3872. end;
  3873. A_SUB:
  3874. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3875. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3876. begin
  3877. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  3878. RemoveInstruction(hp1);
  3879. end;
  3880. A_ADD:
  3881. begin
  3882. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3883. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3884. begin
  3885. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  3886. RemoveInstruction(hp1);
  3887. if (taicpu(p).oper[0]^.val = 0) then
  3888. begin
  3889. hp1 := tai(p.next);
  3890. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  3891. if not GetLastInstruction(hp1, p) then
  3892. p := hp1;
  3893. DoSubAddOpt := True;
  3894. end
  3895. end;
  3896. end;
  3897. else
  3898. ;
  3899. end;
  3900. end;
  3901. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  3902. {$ifdef i386}
  3903. var
  3904. hp1 : tai;
  3905. {$endif i386}
  3906. begin
  3907. Result:=false;
  3908. { * change "subl $2, %esp; pushw x" to "pushl x"}
  3909. { * change "sub/add const1, reg" or "dec reg" followed by
  3910. "sub const2, reg" to one "sub ..., reg" }
  3911. if MatchOpType(taicpu(p),top_const,top_reg) then
  3912. begin
  3913. {$ifdef i386}
  3914. if (taicpu(p).oper[0]^.val = 2) and
  3915. (taicpu(p).oper[1]^.reg = NR_ESP) and
  3916. { Don't do the sub/push optimization if the sub }
  3917. { comes from setting up the stack frame (JM) }
  3918. (not(GetLastInstruction(p,hp1)) or
  3919. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  3920. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  3921. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  3922. begin
  3923. hp1 := tai(p.next);
  3924. while Assigned(hp1) and
  3925. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  3926. not RegReadByInstruction(NR_ESP,hp1) and
  3927. not RegModifiedByInstruction(NR_ESP,hp1) do
  3928. hp1 := tai(hp1.next);
  3929. if Assigned(hp1) and
  3930. MatchInstruction(hp1,A_PUSH,[S_W]) then
  3931. begin
  3932. taicpu(hp1).changeopsize(S_L);
  3933. if taicpu(hp1).oper[0]^.typ=top_reg then
  3934. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  3935. hp1 := tai(p.next);
  3936. RemoveCurrentp(p, hp1);
  3937. Result:=true;
  3938. exit;
  3939. end;
  3940. end;
  3941. {$endif i386}
  3942. if DoSubAddOpt(p) then
  3943. Result:=true;
  3944. end;
  3945. end;
  3946. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  3947. var
  3948. TmpBool1,TmpBool2 : Boolean;
  3949. tmpref : treference;
  3950. hp1,hp2: tai;
  3951. mask: tcgint;
  3952. begin
  3953. Result:=false;
  3954. { All these optimisations work on "shl/sal const,%reg" }
  3955. if not MatchOpType(taicpu(p),top_const,top_reg) then
  3956. Exit;
  3957. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3958. (taicpu(p).oper[0]^.val <= 3) then
  3959. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  3960. begin
  3961. { should we check the next instruction? }
  3962. TmpBool1 := True;
  3963. { have we found an add/sub which could be
  3964. integrated in the lea? }
  3965. TmpBool2 := False;
  3966. reference_reset(tmpref,2,[]);
  3967. TmpRef.index := taicpu(p).oper[1]^.reg;
  3968. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  3969. while TmpBool1 and
  3970. GetNextInstruction(p, hp1) and
  3971. (tai(hp1).typ = ait_instruction) and
  3972. ((((taicpu(hp1).opcode = A_ADD) or
  3973. (taicpu(hp1).opcode = A_SUB)) and
  3974. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  3975. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  3976. (((taicpu(hp1).opcode = A_INC) or
  3977. (taicpu(hp1).opcode = A_DEC)) and
  3978. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  3979. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  3980. ((taicpu(hp1).opcode = A_LEA) and
  3981. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3982. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  3983. (not GetNextInstruction(hp1,hp2) or
  3984. not instrReadsFlags(hp2)) Do
  3985. begin
  3986. TmpBool1 := False;
  3987. if taicpu(hp1).opcode=A_LEA then
  3988. begin
  3989. if (TmpRef.base = NR_NO) and
  3990. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  3991. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  3992. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  3993. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  3994. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  3995. begin
  3996. TmpBool1 := True;
  3997. TmpBool2 := True;
  3998. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  3999. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  4000. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  4001. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  4002. RemoveInstruction(hp1);
  4003. end
  4004. end
  4005. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  4006. begin
  4007. TmpBool1 := True;
  4008. TmpBool2 := True;
  4009. case taicpu(hp1).opcode of
  4010. A_ADD:
  4011. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4012. A_SUB:
  4013. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4014. else
  4015. internalerror(2019050536);
  4016. end;
  4017. RemoveInstruction(hp1);
  4018. end
  4019. else
  4020. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4021. (((taicpu(hp1).opcode = A_ADD) and
  4022. (TmpRef.base = NR_NO)) or
  4023. (taicpu(hp1).opcode = A_INC) or
  4024. (taicpu(hp1).opcode = A_DEC)) then
  4025. begin
  4026. TmpBool1 := True;
  4027. TmpBool2 := True;
  4028. case taicpu(hp1).opcode of
  4029. A_ADD:
  4030. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  4031. A_INC:
  4032. inc(TmpRef.offset);
  4033. A_DEC:
  4034. dec(TmpRef.offset);
  4035. else
  4036. internalerror(2019050535);
  4037. end;
  4038. RemoveInstruction(hp1);
  4039. end;
  4040. end;
  4041. if TmpBool2
  4042. {$ifndef x86_64}
  4043. or
  4044. ((current_settings.optimizecputype < cpu_Pentium2) and
  4045. (taicpu(p).oper[0]^.val <= 3) and
  4046. not(cs_opt_size in current_settings.optimizerswitches))
  4047. {$endif x86_64}
  4048. then
  4049. begin
  4050. if not(TmpBool2) and
  4051. (taicpu(p).oper[0]^.val=1) then
  4052. begin
  4053. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4054. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  4055. end
  4056. else
  4057. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  4058. taicpu(p).oper[1]^.reg);
  4059. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  4060. InsertLLItem(p.previous, p.next, hp1);
  4061. p.free;
  4062. p := hp1;
  4063. end;
  4064. end
  4065. {$ifndef x86_64}
  4066. else if (current_settings.optimizecputype < cpu_Pentium2) then
  4067. begin
  4068. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  4069. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  4070. (unlike shl, which is only Tairable in the U pipe) }
  4071. if taicpu(p).oper[0]^.val=1 then
  4072. begin
  4073. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4074. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  4075. InsertLLItem(p.previous, p.next, hp1);
  4076. p.free;
  4077. p := hp1;
  4078. end
  4079. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  4080. "shl $3, %reg" to "lea (,%reg,8), %reg }
  4081. else if (taicpu(p).opsize = S_L) and
  4082. (taicpu(p).oper[0]^.val<= 3) then
  4083. begin
  4084. reference_reset(tmpref,2,[]);
  4085. TmpRef.index := taicpu(p).oper[1]^.reg;
  4086. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4087. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  4088. InsertLLItem(p.previous, p.next, hp1);
  4089. p.free;
  4090. p := hp1;
  4091. end;
  4092. end
  4093. {$endif x86_64}
  4094. else if
  4095. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  4096. (
  4097. (
  4098. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  4099. SetAndTest(hp1, hp2)
  4100. {$ifdef x86_64}
  4101. ) or
  4102. (
  4103. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4104. GetNextInstruction(hp1, hp2) and
  4105. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  4106. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4107. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  4108. {$endif x86_64}
  4109. )
  4110. ) and
  4111. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  4112. begin
  4113. { Change:
  4114. shl x, %reg1
  4115. mov -(1<<x), %reg2
  4116. and %reg2, %reg1
  4117. Or:
  4118. shl x, %reg1
  4119. and -(1<<x), %reg1
  4120. To just:
  4121. shl x, %reg1
  4122. Since the and operation only zeroes bits that are already zero from the shl operation
  4123. }
  4124. case taicpu(p).oper[0]^.val of
  4125. 8:
  4126. mask:=$FFFFFFFFFFFFFF00;
  4127. 16:
  4128. mask:=$FFFFFFFFFFFF0000;
  4129. 32:
  4130. mask:=$FFFFFFFF00000000;
  4131. 63:
  4132. { Constant pre-calculated to prevent overflow errors with Int64 }
  4133. mask:=$8000000000000000;
  4134. else
  4135. begin
  4136. if taicpu(p).oper[0]^.val >= 64 then
  4137. { Shouldn't happen realistically, since the register
  4138. is guaranteed to be set to zero at this point }
  4139. mask := 0
  4140. else
  4141. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  4142. end;
  4143. end;
  4144. if taicpu(hp1).oper[0]^.val = mask then
  4145. begin
  4146. { Everything checks out, perform the optimisation, as long as
  4147. the FLAGS register isn't being used}
  4148. TransferUsedRegs(TmpUsedRegs);
  4149. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4150. {$ifdef x86_64}
  4151. if (hp1 <> hp2) then
  4152. begin
  4153. { "shl/mov/and" version }
  4154. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4155. { Don't do the optimisation if the FLAGS register is in use }
  4156. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  4157. begin
  4158. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  4159. { Don't remove the 'mov' instruction if its register is used elsewhere }
  4160. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  4161. begin
  4162. RemoveInstruction(hp1);
  4163. Result := True;
  4164. end;
  4165. { Only set Result to True if the 'mov' instruction was removed }
  4166. RemoveInstruction(hp2);
  4167. end;
  4168. end
  4169. else
  4170. {$endif x86_64}
  4171. begin
  4172. { "shl/and" version }
  4173. { Don't do the optimisation if the FLAGS register is in use }
  4174. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  4175. begin
  4176. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  4177. RemoveInstruction(hp1);
  4178. Result := True;
  4179. end;
  4180. end;
  4181. Exit;
  4182. end
  4183. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  4184. begin
  4185. { Even if the mask doesn't allow for its removal, we might be
  4186. able to optimise the mask for the "shl/and" version, which
  4187. may permit other peephole optimisations }
  4188. {$ifdef DEBUG_AOPTCPU}
  4189. mask := taicpu(hp1).oper[0]^.val and mask;
  4190. if taicpu(hp1).oper[0]^.val <> mask then
  4191. begin
  4192. DebugMsg(
  4193. SPeepholeOptimization +
  4194. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  4195. ' to $' + debug_tostr(mask) +
  4196. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  4197. taicpu(hp1).oper[0]^.val := mask;
  4198. end;
  4199. {$else DEBUG_AOPTCPU}
  4200. { If debugging is off, just set the operand even if it's the same }
  4201. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  4202. {$endif DEBUG_AOPTCPU}
  4203. end;
  4204. end;
  4205. end;
  4206. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  4207. var
  4208. CurrentRef: TReference;
  4209. FullReg: TRegister;
  4210. hp1, hp2: tai;
  4211. begin
  4212. Result := False;
  4213. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  4214. Exit;
  4215. { We assume you've checked if the operand is actually a reference by
  4216. this point. If it isn't, you'll most likely get an access violation }
  4217. CurrentRef := first_mov.oper[1]^.ref^;
  4218. { Memory must be aligned }
  4219. if (CurrentRef.offset mod 4) <> 0 then
  4220. Exit;
  4221. Inc(CurrentRef.offset);
  4222. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4223. if MatchOperand(second_mov.oper[0]^, 0) and
  4224. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  4225. GetNextInstruction(second_mov, hp1) and
  4226. (hp1.typ = ait_instruction) and
  4227. (taicpu(hp1).opcode = A_MOV) and
  4228. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4229. (taicpu(hp1).oper[0]^.val = 0) then
  4230. begin
  4231. Inc(CurrentRef.offset);
  4232. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  4233. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  4234. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  4235. begin
  4236. case taicpu(hp1).opsize of
  4237. S_B:
  4238. if GetNextInstruction(hp1, hp2) and
  4239. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  4240. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4241. (taicpu(hp2).oper[0]^.val = 0) then
  4242. begin
  4243. Inc(CurrentRef.offset);
  4244. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4245. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  4246. (taicpu(hp2).opsize = S_B) then
  4247. begin
  4248. RemoveInstruction(hp1);
  4249. RemoveInstruction(hp2);
  4250. first_mov.opsize := S_L;
  4251. if first_mov.oper[0]^.typ = top_reg then
  4252. begin
  4253. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  4254. { Reuse second_mov as a MOVZX instruction }
  4255. second_mov.opcode := A_MOVZX;
  4256. second_mov.opsize := S_BL;
  4257. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4258. second_mov.loadreg(1, FullReg);
  4259. first_mov.oper[0]^.reg := FullReg;
  4260. asml.Remove(second_mov);
  4261. asml.InsertBefore(second_mov, first_mov);
  4262. end
  4263. else
  4264. { It's a value }
  4265. begin
  4266. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  4267. RemoveInstruction(second_mov);
  4268. end;
  4269. Result := True;
  4270. Exit;
  4271. end;
  4272. end;
  4273. S_W:
  4274. begin
  4275. RemoveInstruction(hp1);
  4276. first_mov.opsize := S_L;
  4277. if first_mov.oper[0]^.typ = top_reg then
  4278. begin
  4279. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  4280. { Reuse second_mov as a MOVZX instruction }
  4281. second_mov.opcode := A_MOVZX;
  4282. second_mov.opsize := S_BL;
  4283. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4284. second_mov.loadreg(1, FullReg);
  4285. first_mov.oper[0]^.reg := FullReg;
  4286. asml.Remove(second_mov);
  4287. asml.InsertBefore(second_mov, first_mov);
  4288. end
  4289. else
  4290. { It's a value }
  4291. begin
  4292. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  4293. RemoveInstruction(second_mov);
  4294. end;
  4295. Result := True;
  4296. Exit;
  4297. end;
  4298. else
  4299. ;
  4300. end;
  4301. end;
  4302. end;
  4303. end;
  4304. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  4305. { returns true if a "continue" should be done after this optimization }
  4306. var
  4307. hp1, hp2: tai;
  4308. begin
  4309. Result := false;
  4310. if MatchOpType(taicpu(p),top_ref) and
  4311. GetNextInstruction(p, hp1) and
  4312. (hp1.typ = ait_instruction) and
  4313. (((taicpu(hp1).opcode = A_FLD) and
  4314. (taicpu(p).opcode = A_FSTP)) or
  4315. ((taicpu(p).opcode = A_FISTP) and
  4316. (taicpu(hp1).opcode = A_FILD))) and
  4317. MatchOpType(taicpu(hp1),top_ref) and
  4318. (taicpu(hp1).opsize = taicpu(p).opsize) and
  4319. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4320. begin
  4321. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  4322. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  4323. GetNextInstruction(hp1, hp2) and
  4324. (hp2.typ = ait_instruction) and
  4325. IsExitCode(hp2) and
  4326. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  4327. not(assigned(current_procinfo.procdef.funcretsym) and
  4328. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  4329. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  4330. begin
  4331. RemoveInstruction(hp1);
  4332. RemoveCurrentP(p, hp2);
  4333. RemoveLastDeallocForFuncRes(p);
  4334. Result := true;
  4335. end
  4336. else
  4337. { we can do this only in fast math mode as fstp is rounding ...
  4338. ... still disabled as it breaks the compiler and/or rtl }
  4339. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  4340. { ... or if another fstp equal to the first one follows }
  4341. (GetNextInstruction(hp1,hp2) and
  4342. (hp2.typ = ait_instruction) and
  4343. (taicpu(p).opcode=taicpu(hp2).opcode) and
  4344. (taicpu(p).opsize=taicpu(hp2).opsize))
  4345. ) and
  4346. { fst can't store an extended/comp value }
  4347. (taicpu(p).opsize <> S_FX) and
  4348. (taicpu(p).opsize <> S_IQ) then
  4349. begin
  4350. if (taicpu(p).opcode = A_FSTP) then
  4351. taicpu(p).opcode := A_FST
  4352. else
  4353. taicpu(p).opcode := A_FIST;
  4354. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  4355. RemoveInstruction(hp1);
  4356. end;
  4357. end;
  4358. end;
  4359. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  4360. var
  4361. hp1, hp2: tai;
  4362. begin
  4363. result:=false;
  4364. if MatchOpType(taicpu(p),top_reg) and
  4365. GetNextInstruction(p, hp1) and
  4366. (hp1.typ = Ait_Instruction) and
  4367. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4368. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  4369. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  4370. { change to
  4371. fld reg fxxx reg,st
  4372. fxxxp st, st1 (hp1)
  4373. Remark: non commutative operations must be reversed!
  4374. }
  4375. begin
  4376. case taicpu(hp1).opcode Of
  4377. A_FMULP,A_FADDP,
  4378. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4379. begin
  4380. case taicpu(hp1).opcode Of
  4381. A_FADDP: taicpu(hp1).opcode := A_FADD;
  4382. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  4383. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  4384. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  4385. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  4386. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  4387. else
  4388. internalerror(2019050534);
  4389. end;
  4390. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  4391. taicpu(hp1).oper[1]^.reg := NR_ST;
  4392. RemoveCurrentP(p, hp1);
  4393. Result:=true;
  4394. exit;
  4395. end;
  4396. else
  4397. ;
  4398. end;
  4399. end
  4400. else
  4401. if MatchOpType(taicpu(p),top_ref) and
  4402. GetNextInstruction(p, hp2) and
  4403. (hp2.typ = Ait_Instruction) and
  4404. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4405. (taicpu(p).opsize in [S_FS, S_FL]) and
  4406. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  4407. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  4408. if GetLastInstruction(p, hp1) and
  4409. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  4410. MatchOpType(taicpu(hp1),top_ref) and
  4411. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4412. if ((taicpu(hp2).opcode = A_FMULP) or
  4413. (taicpu(hp2).opcode = A_FADDP)) then
  4414. { change to
  4415. fld/fst mem1 (hp1) fld/fst mem1
  4416. fld mem1 (p) fadd/
  4417. faddp/ fmul st, st
  4418. fmulp st, st1 (hp2) }
  4419. begin
  4420. RemoveCurrentP(p, hp1);
  4421. if (taicpu(hp2).opcode = A_FADDP) then
  4422. taicpu(hp2).opcode := A_FADD
  4423. else
  4424. taicpu(hp2).opcode := A_FMUL;
  4425. taicpu(hp2).oper[1]^.reg := NR_ST;
  4426. end
  4427. else
  4428. { change to
  4429. fld/fst mem1 (hp1) fld/fst mem1
  4430. fld mem1 (p) fld st}
  4431. begin
  4432. taicpu(p).changeopsize(S_FL);
  4433. taicpu(p).loadreg(0,NR_ST);
  4434. end
  4435. else
  4436. begin
  4437. case taicpu(hp2).opcode Of
  4438. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4439. { change to
  4440. fld/fst mem1 (hp1) fld/fst mem1
  4441. fld mem2 (p) fxxx mem2
  4442. fxxxp st, st1 (hp2) }
  4443. begin
  4444. case taicpu(hp2).opcode Of
  4445. A_FADDP: taicpu(p).opcode := A_FADD;
  4446. A_FMULP: taicpu(p).opcode := A_FMUL;
  4447. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  4448. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  4449. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  4450. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  4451. else
  4452. internalerror(2019050533);
  4453. end;
  4454. RemoveInstruction(hp2);
  4455. end
  4456. else
  4457. ;
  4458. end
  4459. end
  4460. end;
  4461. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  4462. begin
  4463. Result := condition_in(cond1, cond2) or
  4464. { Not strictly subsets due to the actual flags checked, but because we're
  4465. comparing integers, E is a subset of AE and GE and their aliases }
  4466. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  4467. end;
  4468. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  4469. var
  4470. v: TCGInt;
  4471. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  4472. FirstMatch: Boolean;
  4473. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  4474. begin
  4475. Result:=false;
  4476. { All these optimisations need a next instruction }
  4477. if not GetNextInstruction(p, hp1) then
  4478. Exit;
  4479. { Search for:
  4480. cmp ###,###
  4481. j(c1) @lbl1
  4482. ...
  4483. @lbl:
  4484. cmp ###.### (same comparison as above)
  4485. j(c2) @lbl2
  4486. If c1 is a subset of c2, change to:
  4487. cmp ###,###
  4488. j(c2) @lbl2
  4489. (@lbl1 may become a dead label as a result)
  4490. }
  4491. { Also handle cases where there are multiple jumps in a row }
  4492. p_jump := hp1;
  4493. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  4494. begin
  4495. if IsJumpToLabel(taicpu(p_jump)) then
  4496. begin
  4497. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  4498. p_label := nil;
  4499. if Assigned(JumpLabel) then
  4500. p_label := getlabelwithsym(JumpLabel);
  4501. if Assigned(p_label) and
  4502. GetNextInstruction(p_label, p_dist) and
  4503. MatchInstruction(p_dist, A_CMP, []) and
  4504. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  4505. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4506. GetNextInstruction(p_dist, hp1_dist) and
  4507. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4508. begin
  4509. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4510. if JumpLabel = JumpLabel_dist then
  4511. { This is an infinite loop }
  4512. Exit;
  4513. { Best optimisation when the first condition is a subset (or equal) of the second }
  4514. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  4515. begin
  4516. { Any registers used here will already be allocated }
  4517. if Assigned(JumpLabel_dist) then
  4518. JumpLabel_dist.IncRefs;
  4519. if Assigned(JumpLabel) then
  4520. JumpLabel.DecRefs;
  4521. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  4522. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  4523. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4524. Result := True;
  4525. { Don't exit yet. Since p and p_jump haven't actually been
  4526. removed, we can check for more on this iteration }
  4527. end
  4528. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  4529. GetNextInstruction(hp1_dist, hp1_label) and
  4530. SkipAligns(hp1_label, hp1_label) and
  4531. (hp1_label.typ = ait_label) then
  4532. begin
  4533. JumpLabel_far := tai_label(hp1_label).labsym;
  4534. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  4535. { This is an infinite loop }
  4536. Exit;
  4537. if Assigned(JumpLabel_far) then
  4538. begin
  4539. { In this situation, if the first jump branches, the second one will never,
  4540. branch so change the destination label to after the second jump }
  4541. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  4542. if Assigned(JumpLabel) then
  4543. JumpLabel.DecRefs;
  4544. JumpLabel_far.IncRefs;
  4545. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  4546. Result := True;
  4547. { Don't exit yet. Since p and p_jump haven't actually been
  4548. removed, we can check for more on this iteration }
  4549. Continue;
  4550. end;
  4551. end;
  4552. end;
  4553. end;
  4554. { Search for:
  4555. cmp ###,###
  4556. j(c1) @lbl1
  4557. cmp ###,### (same as first)
  4558. Remove second cmp
  4559. }
  4560. if GetNextInstruction(p_jump, hp2) and
  4561. (
  4562. (
  4563. MatchInstruction(hp2, A_CMP, []) and
  4564. (
  4565. (
  4566. MatchOpType(taicpu(p), top_const, top_reg) and
  4567. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  4568. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  4569. ) or (
  4570. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  4571. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  4572. )
  4573. )
  4574. ) or (
  4575. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  4576. MatchOperand(taicpu(p).oper[0]^, 0) and
  4577. (taicpu(p).oper[1]^.typ = top_reg) and
  4578. MatchInstruction(hp2, A_TEST, []) and
  4579. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4580. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  4581. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  4582. )
  4583. ) then
  4584. begin
  4585. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  4586. RemoveInstruction(hp2);
  4587. Result := True;
  4588. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  4589. end;
  4590. GetNextInstruction(p_jump, p_jump);
  4591. end;
  4592. if taicpu(p).oper[0]^.typ = top_const then
  4593. begin
  4594. if (taicpu(p).oper[0]^.val = 0) and
  4595. (taicpu(p).oper[1]^.typ = top_reg) and
  4596. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  4597. begin
  4598. hp2 := p;
  4599. FirstMatch := True;
  4600. { When dealing with "cmp $0,%reg", only ZF and SF contain
  4601. anything meaningful once it's converted to "test %reg,%reg";
  4602. additionally, some jumps will always (or never) branch, so
  4603. evaluate every jump immediately following the
  4604. comparison, optimising the conditions if possible.
  4605. Similarly with SETcc... those that are always set to 0 or 1
  4606. are changed to MOV instructions }
  4607. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  4608. (
  4609. GetNextInstruction(hp2, hp1) and
  4610. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  4611. ) do
  4612. begin
  4613. FirstMatch := False;
  4614. case taicpu(hp1).condition of
  4615. C_B, C_C, C_NAE, C_O:
  4616. { For B/NAE:
  4617. Will never branch since an unsigned integer can never be below zero
  4618. For C/O:
  4619. Result cannot overflow because 0 is being subtracted
  4620. }
  4621. begin
  4622. if taicpu(hp1).opcode = A_Jcc then
  4623. begin
  4624. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  4625. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  4626. RemoveInstruction(hp1);
  4627. { Since hp1 was deleted, hp2 must not be updated }
  4628. Continue;
  4629. end
  4630. else
  4631. begin
  4632. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  4633. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  4634. taicpu(hp1).opcode := A_MOV;
  4635. taicpu(hp1).ops := 2;
  4636. taicpu(hp1).condition := C_None;
  4637. taicpu(hp1).opsize := S_B;
  4638. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4639. taicpu(hp1).loadconst(0, 0);
  4640. end;
  4641. end;
  4642. C_BE, C_NA:
  4643. begin
  4644. { Will only branch if equal to zero }
  4645. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  4646. taicpu(hp1).condition := C_E;
  4647. end;
  4648. C_A, C_NBE:
  4649. begin
  4650. { Will only branch if not equal to zero }
  4651. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  4652. taicpu(hp1).condition := C_NE;
  4653. end;
  4654. C_AE, C_NB, C_NC, C_NO:
  4655. begin
  4656. { Will always branch }
  4657. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  4658. if taicpu(hp1).opcode = A_Jcc then
  4659. begin
  4660. MakeUnconditional(taicpu(hp1));
  4661. { Any jumps/set that follow will now be dead code }
  4662. RemoveDeadCodeAfterJump(taicpu(hp1));
  4663. Break;
  4664. end
  4665. else
  4666. begin
  4667. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  4668. taicpu(hp1).opcode := A_MOV;
  4669. taicpu(hp1).ops := 2;
  4670. taicpu(hp1).condition := C_None;
  4671. taicpu(hp1).opsize := S_B;
  4672. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4673. taicpu(hp1).loadconst(0, 1);
  4674. end;
  4675. end;
  4676. C_None:
  4677. InternalError(2020012201);
  4678. C_P, C_PE, C_NP, C_PO:
  4679. { We can't handle parity checks and they should never be generated
  4680. after a general-purpose CMP (it's used in some floating-point
  4681. comparisons that don't use CMP) }
  4682. InternalError(2020012202);
  4683. else
  4684. { Zero/Equality, Sign, their complements and all of the
  4685. signed comparisons do not need to be converted };
  4686. end;
  4687. hp2 := hp1;
  4688. end;
  4689. { Convert the instruction to a TEST }
  4690. taicpu(p).opcode := A_TEST;
  4691. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  4692. Result := True;
  4693. Exit;
  4694. end
  4695. else if (taicpu(p).oper[0]^.val = 1) and
  4696. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  4697. (taicpu(hp1).condition in [C_L, C_NGE]) then
  4698. begin
  4699. { Convert; To:
  4700. cmp $1,r/m cmp $0,r/m
  4701. jl @lbl jle @lbl
  4702. }
  4703. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  4704. taicpu(p).oper[0]^.val := 0;
  4705. taicpu(hp1).condition := C_LE;
  4706. { If the instruction is now "cmp $0,%reg", convert it to a
  4707. TEST (and effectively do the work of the "cmp $0,%reg" in
  4708. the block above)
  4709. If it's a reference, we can get away with not setting
  4710. Result to True because he haven't evaluated the jump
  4711. in this pass yet.
  4712. }
  4713. if (taicpu(p).oper[1]^.typ = top_reg) then
  4714. begin
  4715. taicpu(p).opcode := A_TEST;
  4716. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  4717. Result := True;
  4718. end;
  4719. Exit;
  4720. end
  4721. else if (taicpu(p).oper[1]^.typ = top_reg) then
  4722. begin
  4723. { cmp register,$8000 neg register
  4724. je target --> jo target
  4725. .... only if register is deallocated before jump.}
  4726. case Taicpu(p).opsize of
  4727. S_B: v:=$80;
  4728. S_W: v:=$8000;
  4729. S_L: v:=qword($80000000);
  4730. { S_Q will never happen: cmp with 64 bit constants is not possible }
  4731. S_Q:
  4732. Exit;
  4733. else
  4734. internalerror(2013112905);
  4735. end;
  4736. if (taicpu(p).oper[0]^.val=v) and
  4737. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  4738. (Taicpu(hp1).condition in [C_E,C_NE]) then
  4739. begin
  4740. TransferUsedRegs(TmpUsedRegs);
  4741. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  4742. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  4743. begin
  4744. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  4745. Taicpu(p).opcode:=A_NEG;
  4746. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  4747. Taicpu(p).clearop(1);
  4748. Taicpu(p).ops:=1;
  4749. if Taicpu(hp1).condition=C_E then
  4750. Taicpu(hp1).condition:=C_O
  4751. else
  4752. Taicpu(hp1).condition:=C_NO;
  4753. Result:=true;
  4754. exit;
  4755. end;
  4756. end;
  4757. end;
  4758. end;
  4759. if (taicpu(p).oper[1]^.typ = top_reg) and
  4760. MatchInstruction(hp1,A_MOV,[]) and
  4761. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  4762. (
  4763. (taicpu(p).oper[0]^.typ <> top_reg) or
  4764. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  4765. ) then
  4766. begin
  4767. { If we have something like:
  4768. cmp ###,%reg1
  4769. mov 0,%reg2
  4770. And no registers are shared, move the MOV command to before the
  4771. comparison as this means it can be optimised without worrying
  4772. about the FLAGS register. (This combination is generated by
  4773. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  4774. }
  4775. SwapMovCmp(p, hp1);
  4776. Result := True;
  4777. Exit;
  4778. end;
  4779. end;
  4780. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  4781. var
  4782. hp1: tai;
  4783. begin
  4784. {
  4785. remove the second (v)pxor from
  4786. pxor reg,reg
  4787. ...
  4788. pxor reg,reg
  4789. }
  4790. Result:=false;
  4791. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  4792. MatchOpType(taicpu(p),top_reg,top_reg) and
  4793. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4794. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4795. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4796. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  4797. begin
  4798. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  4799. RemoveInstruction(hp1);
  4800. Result:=true;
  4801. Exit;
  4802. end
  4803. {
  4804. replace
  4805. pxor reg1,reg1
  4806. movapd/s reg1,reg2
  4807. dealloc reg1
  4808. by
  4809. pxor reg2,reg2
  4810. }
  4811. else if GetNextInstruction(p,hp1) and
  4812. { we mix single and double opperations here because we assume that the compiler
  4813. generates vmovapd only after double operations and vmovaps only after single operations }
  4814. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4815. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  4816. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4817. (taicpu(p).oper[0]^.typ=top_reg) then
  4818. begin
  4819. TransferUsedRegs(TmpUsedRegs);
  4820. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4821. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4822. begin
  4823. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  4824. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4825. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  4826. RemoveInstruction(hp1);
  4827. result:=true;
  4828. end;
  4829. end;
  4830. end;
  4831. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  4832. var
  4833. hp1: tai;
  4834. begin
  4835. {
  4836. remove the second (v)pxor from
  4837. (v)pxor reg,reg
  4838. ...
  4839. (v)pxor reg,reg
  4840. }
  4841. Result:=false;
  4842. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  4843. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  4844. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4845. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4846. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4847. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  4848. begin
  4849. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  4850. RemoveInstruction(hp1);
  4851. Result:=true;
  4852. Exit;
  4853. end
  4854. else
  4855. Result:=OptPass1VOP(p);
  4856. end;
  4857. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  4858. var
  4859. hp1 : tai;
  4860. begin
  4861. result:=false;
  4862. { replace
  4863. IMul const,%mreg1,%mreg2
  4864. Mov %reg2,%mreg3
  4865. dealloc %mreg3
  4866. by
  4867. Imul const,%mreg1,%mreg23
  4868. }
  4869. if (taicpu(p).ops=3) and
  4870. GetNextInstruction(p,hp1) and
  4871. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4872. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  4873. (taicpu(hp1).oper[1]^.typ=top_reg) then
  4874. begin
  4875. TransferUsedRegs(TmpUsedRegs);
  4876. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4877. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  4878. begin
  4879. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  4880. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  4881. RemoveInstruction(hp1);
  4882. result:=true;
  4883. end;
  4884. end;
  4885. end;
  4886. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  4887. var
  4888. hp1 : tai;
  4889. begin
  4890. result:=false;
  4891. { replace
  4892. IMul %reg0,%reg1,%reg2
  4893. Mov %reg2,%reg3
  4894. dealloc %reg2
  4895. by
  4896. Imul %reg0,%reg1,%reg3
  4897. }
  4898. if GetNextInstruction(p,hp1) and
  4899. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4900. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  4901. (taicpu(hp1).oper[1]^.typ=top_reg) then
  4902. begin
  4903. TransferUsedRegs(TmpUsedRegs);
  4904. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4905. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  4906. begin
  4907. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  4908. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  4909. RemoveInstruction(hp1);
  4910. result:=true;
  4911. end;
  4912. end;
  4913. end;
  4914. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  4915. var
  4916. hp1, hp2, hp3, hp4, hp5: tai;
  4917. ThisReg: TRegister;
  4918. begin
  4919. Result := False;
  4920. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  4921. Exit;
  4922. {
  4923. convert
  4924. j<c> .L1
  4925. mov 1,reg
  4926. jmp .L2
  4927. .L1
  4928. mov 0,reg
  4929. .L2
  4930. into
  4931. mov 0,reg
  4932. set<not(c)> reg
  4933. take care of alignment and that the mov 0,reg is not converted into a xor as this
  4934. would destroy the flag contents
  4935. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  4936. executed at the same time as a previous comparison.
  4937. set<not(c)> reg
  4938. movzx reg, reg
  4939. }
  4940. if MatchInstruction(hp1,A_MOV,[]) and
  4941. (taicpu(hp1).oper[0]^.typ = top_const) and
  4942. (
  4943. (
  4944. (taicpu(hp1).oper[1]^.typ = top_reg)
  4945. {$ifdef i386}
  4946. { Under i386, ESI, EDI, EBP and ESP
  4947. don't have an 8-bit representation }
  4948. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  4949. {$endif i386}
  4950. ) or (
  4951. {$ifdef i386}
  4952. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  4953. {$endif i386}
  4954. (taicpu(hp1).opsize = S_B)
  4955. )
  4956. ) and
  4957. GetNextInstruction(hp1,hp2) and
  4958. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  4959. GetNextInstruction(hp2,hp3) and
  4960. SkipAligns(hp3, hp3) and
  4961. (hp3.typ=ait_label) and
  4962. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  4963. GetNextInstruction(hp3,hp4) and
  4964. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  4965. (taicpu(hp4).oper[0]^.typ = top_const) and
  4966. (
  4967. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  4968. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  4969. ) and
  4970. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  4971. GetNextInstruction(hp4,hp5) and
  4972. SkipAligns(hp5, hp5) and
  4973. (hp5.typ=ait_label) and
  4974. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  4975. begin
  4976. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  4977. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  4978. tai_label(hp3).labsym.DecRefs;
  4979. { If this isn't the only reference to the middle label, we can
  4980. still make a saving - only that the first jump and everything
  4981. that follows will remain. }
  4982. if (tai_label(hp3).labsym.getrefs = 0) then
  4983. begin
  4984. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  4985. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  4986. else
  4987. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  4988. { remove jump, first label and second MOV (also catching any aligns) }
  4989. repeat
  4990. if not GetNextInstruction(hp2, hp3) then
  4991. InternalError(2021040810);
  4992. RemoveInstruction(hp2);
  4993. hp2 := hp3;
  4994. until hp2 = hp5;
  4995. { Don't decrement reference count before the removal loop
  4996. above, otherwise GetNextInstruction won't stop on the
  4997. the label }
  4998. tai_label(hp5).labsym.DecRefs;
  4999. end
  5000. else
  5001. begin
  5002. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5003. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  5004. else
  5005. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  5006. end;
  5007. taicpu(p).opcode:=A_SETcc;
  5008. taicpu(p).opsize:=S_B;
  5009. taicpu(p).is_jmp:=False;
  5010. if taicpu(hp1).opsize=S_B then
  5011. begin
  5012. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  5013. RemoveInstruction(hp1);
  5014. end
  5015. else
  5016. begin
  5017. { Will be a register because the size can't be S_B otherwise }
  5018. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  5019. taicpu(p).loadreg(0, ThisReg);
  5020. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  5021. begin
  5022. case taicpu(hp1).opsize of
  5023. S_W:
  5024. taicpu(hp1).opsize := S_BW;
  5025. S_L:
  5026. taicpu(hp1).opsize := S_BL;
  5027. {$ifdef x86_64}
  5028. S_Q:
  5029. begin
  5030. taicpu(hp1).opsize := S_BL;
  5031. { Change the destination register to 32-bit }
  5032. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  5033. end;
  5034. {$endif x86_64}
  5035. else
  5036. InternalError(2021040820);
  5037. end;
  5038. taicpu(hp1).opcode := A_MOVZX;
  5039. taicpu(hp1).loadreg(0, ThisReg);
  5040. end
  5041. else
  5042. begin
  5043. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  5044. { hp1 is already a MOV instruction with the correct register }
  5045. taicpu(hp1).loadconst(0, 0);
  5046. { Inserting it right before p will guarantee that the flags are also tracked }
  5047. asml.Remove(hp1);
  5048. asml.InsertBefore(hp1, p);
  5049. end;
  5050. end;
  5051. Result:=true;
  5052. exit;
  5053. end
  5054. end;
  5055. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  5056. var
  5057. hp2, hp3, first_assignment: tai;
  5058. IncCount, OperIdx: Integer;
  5059. OrigLabel: TAsmLabel;
  5060. begin
  5061. Count := 0;
  5062. Result := False;
  5063. first_assignment := nil;
  5064. if (LoopCount >= 20) then
  5065. begin
  5066. { Guard against infinite loops }
  5067. Exit;
  5068. end;
  5069. if (taicpu(p).oper[0]^.typ <> top_ref) or
  5070. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  5071. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  5072. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  5073. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  5074. Exit;
  5075. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  5076. {
  5077. change
  5078. jmp .L1
  5079. ...
  5080. .L1:
  5081. mov ##, ## ( multiple movs possible )
  5082. jmp/ret
  5083. into
  5084. mov ##, ##
  5085. jmp/ret
  5086. }
  5087. if not Assigned(hp1) then
  5088. begin
  5089. hp1 := GetLabelWithSym(OrigLabel);
  5090. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  5091. Exit;
  5092. end;
  5093. hp2 := hp1;
  5094. while Assigned(hp2) do
  5095. begin
  5096. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  5097. SkipLabels(hp2,hp2);
  5098. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  5099. Break;
  5100. case taicpu(hp2).opcode of
  5101. A_MOVSS:
  5102. begin
  5103. if taicpu(hp2).ops = 0 then
  5104. { Wrong MOVSS }
  5105. Break;
  5106. Inc(Count);
  5107. if Count >= 5 then
  5108. { Too many to be worthwhile }
  5109. Break;
  5110. GetNextInstruction(hp2, hp2);
  5111. Continue;
  5112. end;
  5113. A_MOV,
  5114. A_MOVD,
  5115. A_MOVQ,
  5116. A_MOVSX,
  5117. {$ifdef x86_64}
  5118. A_MOVSXD,
  5119. {$endif x86_64}
  5120. A_MOVZX,
  5121. A_MOVAPS,
  5122. A_MOVUPS,
  5123. A_MOVSD,
  5124. A_MOVAPD,
  5125. A_MOVUPD,
  5126. A_MOVDQA,
  5127. A_MOVDQU,
  5128. A_VMOVSS,
  5129. A_VMOVAPS,
  5130. A_VMOVUPS,
  5131. A_VMOVSD,
  5132. A_VMOVAPD,
  5133. A_VMOVUPD,
  5134. A_VMOVDQA,
  5135. A_VMOVDQU:
  5136. begin
  5137. Inc(Count);
  5138. if Count >= 5 then
  5139. { Too many to be worthwhile }
  5140. Break;
  5141. GetNextInstruction(hp2, hp2);
  5142. Continue;
  5143. end;
  5144. A_JMP:
  5145. begin
  5146. { Guard against infinite loops }
  5147. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  5148. Exit;
  5149. { Analyse this jump first in case it also duplicates assignments }
  5150. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  5151. begin
  5152. { Something did change! }
  5153. Result := True;
  5154. Inc(Count, IncCount);
  5155. if Count >= 5 then
  5156. begin
  5157. { Too many to be worthwhile }
  5158. Exit;
  5159. end;
  5160. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  5161. Break;
  5162. end;
  5163. Result := True;
  5164. Break;
  5165. end;
  5166. A_RET:
  5167. begin
  5168. Result := True;
  5169. Break;
  5170. end;
  5171. else
  5172. Break;
  5173. end;
  5174. end;
  5175. if Result then
  5176. begin
  5177. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  5178. if Count = 0 then
  5179. begin
  5180. Result := False;
  5181. Exit;
  5182. end;
  5183. hp3 := p;
  5184. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  5185. while True do
  5186. begin
  5187. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  5188. SkipLabels(hp1,hp1);
  5189. if (hp1.typ <> ait_instruction) then
  5190. InternalError(2021040720);
  5191. case taicpu(hp1).opcode of
  5192. A_JMP:
  5193. begin
  5194. { Change the original jump to the new destination }
  5195. OrigLabel.decrefs;
  5196. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  5197. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  5198. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5199. if not Assigned(first_assignment) then
  5200. InternalError(2021040810)
  5201. else
  5202. p := first_assignment;
  5203. Exit;
  5204. end;
  5205. A_RET:
  5206. begin
  5207. { Now change the jump into a RET instruction }
  5208. ConvertJumpToRET(p, hp1);
  5209. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5210. if not Assigned(first_assignment) then
  5211. InternalError(2021040811)
  5212. else
  5213. p := first_assignment;
  5214. Exit;
  5215. end;
  5216. else
  5217. begin
  5218. { Duplicate the MOV instruction }
  5219. hp3:=tai(hp1.getcopy);
  5220. if first_assignment = nil then
  5221. first_assignment := hp3;
  5222. asml.InsertBefore(hp3, p);
  5223. { Make sure the compiler knows about any final registers written here }
  5224. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  5225. with taicpu(hp3).oper[OperIdx]^ do
  5226. begin
  5227. case typ of
  5228. top_ref:
  5229. begin
  5230. if (ref^.base <> NR_NO) and
  5231. (getsupreg(ref^.base) <> RS_ESP) and
  5232. (getsupreg(ref^.base) <> RS_EBP)
  5233. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  5234. then
  5235. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  5236. if (ref^.index <> NR_NO) and
  5237. (getsupreg(ref^.index) <> RS_ESP) and
  5238. (getsupreg(ref^.index) <> RS_EBP)
  5239. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  5240. (ref^.index <> ref^.base) then
  5241. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  5242. end;
  5243. top_reg:
  5244. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  5245. else
  5246. ;
  5247. end;
  5248. end;
  5249. end;
  5250. end;
  5251. if not GetNextInstruction(hp1, hp1) then
  5252. { Should have dropped out earlier }
  5253. InternalError(2021040710);
  5254. end;
  5255. end;
  5256. end;
  5257. procedure TX86AsmOptimizer.SwapMovCmp(var p, hp1: tai);
  5258. var
  5259. hp2: tai;
  5260. X: Integer;
  5261. begin
  5262. asml.Remove(hp1);
  5263. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  5264. if not GetLastInstruction(p, hp2) then
  5265. asml.InsertBefore(hp1, p)
  5266. else
  5267. asml.InsertAfter(hp1, hp2);
  5268. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and mov instructions to improve optimisation potential', hp1);
  5269. for X := 0 to 1 do
  5270. case taicpu(hp1).oper[X]^.typ of
  5271. top_reg:
  5272. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  5273. top_ref:
  5274. begin
  5275. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  5276. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  5277. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  5278. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  5279. end;
  5280. else
  5281. ;
  5282. end;
  5283. end;
  5284. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  5285. function IsXCHGAcceptable: Boolean; inline;
  5286. begin
  5287. { Always accept if optimising for size }
  5288. Result := (cs_opt_size in current_settings.optimizerswitches) or
  5289. (
  5290. {$ifdef x86_64}
  5291. { XCHG takes 3 cycles on AMD Athlon64 }
  5292. (current_settings.optimizecputype >= cpu_core_i)
  5293. {$else x86_64}
  5294. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  5295. than 3, so it becomes a saving compared to three MOVs with two of
  5296. them able to execute simultaneously. [Kit] }
  5297. (current_settings.optimizecputype >= cpu_PentiumM)
  5298. {$endif x86_64}
  5299. );
  5300. end;
  5301. var
  5302. NewRef: TReference;
  5303. hp1, hp2, hp3, hp4: Tai;
  5304. {$ifndef x86_64}
  5305. OperIdx: Integer;
  5306. {$endif x86_64}
  5307. NewInstr : Taicpu;
  5308. NewAligh : Tai_align;
  5309. DestLabel: TAsmLabel;
  5310. begin
  5311. Result:=false;
  5312. { This optimisation adds an instruction, so only do it for speed }
  5313. if not (cs_opt_size in current_settings.optimizerswitches) and
  5314. MatchOpType(taicpu(p), top_const, top_reg) and
  5315. (taicpu(p).oper[0]^.val = 0) then
  5316. begin
  5317. { To avoid compiler warning }
  5318. DestLabel := nil;
  5319. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  5320. InternalError(2021040750);
  5321. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  5322. Exit;
  5323. case hp1.typ of
  5324. ait_label:
  5325. begin
  5326. { Change:
  5327. mov $0,%reg mov $0,%reg
  5328. @Lbl1: @Lbl1:
  5329. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  5330. je @Lbl2 jne @Lbl2
  5331. To: To:
  5332. mov $0,%reg mov $0,%reg
  5333. jmp @Lbl2 jmp @Lbl3
  5334. (align) (align)
  5335. @Lbl1: @Lbl1:
  5336. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  5337. je @Lbl2 je @Lbl2
  5338. @Lbl3: <-- Only if label exists
  5339. (Not if it's optimised for size)
  5340. }
  5341. if not GetNextInstruction(hp1, hp2) then
  5342. Exit;
  5343. if not (cs_opt_size in current_settings.optimizerswitches) and
  5344. (hp2.typ = ait_instruction) and
  5345. (
  5346. { Register sizes must exactly match }
  5347. (
  5348. (taicpu(hp2).opcode = A_CMP) and
  5349. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  5350. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5351. ) or (
  5352. (taicpu(hp2).opcode = A_TEST) and
  5353. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5354. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5355. )
  5356. ) and GetNextInstruction(hp2, hp3) and
  5357. (hp3.typ = ait_instruction) and
  5358. (taicpu(hp3).opcode = A_JCC) and
  5359. (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
  5360. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  5361. begin
  5362. { Check condition of jump }
  5363. { Always true? }
  5364. if condition_in(C_E, taicpu(hp3).condition) then
  5365. begin
  5366. { Copy label symbol and obtain matching label entry for the
  5367. conditional jump, as this will be our destination}
  5368. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  5369. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  5370. Result := True;
  5371. end
  5372. { Always false? }
  5373. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  5374. begin
  5375. { This is only worth it if there's a jump to take }
  5376. case hp2.typ of
  5377. ait_instruction:
  5378. begin
  5379. if taicpu(hp2).opcode = A_JMP then
  5380. begin
  5381. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5382. { An unconditional jump follows the conditional jump which will always be false,
  5383. so use this jump's destination for the new jump }
  5384. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  5385. Result := True;
  5386. end
  5387. else if taicpu(hp2).opcode = A_JCC then
  5388. begin
  5389. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5390. if condition_in(C_E, taicpu(hp2).condition) then
  5391. begin
  5392. { A second conditional jump follows the conditional jump which will always be false,
  5393. while the second jump is always True, so use this jump's destination for the new jump }
  5394. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  5395. Result := True;
  5396. end;
  5397. { Don't risk it if the jump isn't always true (Result remains False) }
  5398. end;
  5399. end;
  5400. else
  5401. { If anything else don't optimise };
  5402. end;
  5403. end;
  5404. if Result then
  5405. begin
  5406. { Just so we have something to insert as a paremeter}
  5407. reference_reset(NewRef, 1, []);
  5408. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  5409. { Now actually load the correct parameter }
  5410. NewInstr.loadsymbol(0, DestLabel, 0);
  5411. { Get instruction before original label (may not be p under -O3) }
  5412. if not GetLastInstruction(hp1, hp2) then
  5413. { Shouldn't fail here }
  5414. InternalError(2021040701);
  5415. DestLabel.increfs;
  5416. AsmL.InsertAfter(NewInstr, hp2);
  5417. { Add new alignment field }
  5418. (* AsmL.InsertAfter(
  5419. cai_align.create_max(
  5420. current_settings.alignment.jumpalign,
  5421. current_settings.alignment.jumpalignskipmax
  5422. ),
  5423. NewInstr
  5424. ); *)
  5425. end;
  5426. Exit;
  5427. end;
  5428. end;
  5429. else
  5430. ;
  5431. end;
  5432. end;
  5433. if not GetNextInstruction(p, hp1) then
  5434. Exit;
  5435. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  5436. begin
  5437. { Sometimes the MOVs that OptPass2JMP produces can be improved
  5438. further, but we can't just put this jump optimisation in pass 1
  5439. because it tends to perform worse when conditional jumps are
  5440. nearby (e.g. when converting CMOV instructions). [Kit] }
  5441. if OptPass2JMP(hp1) then
  5442. { call OptPass1MOV once to potentially merge any MOVs that were created }
  5443. Result := OptPass1MOV(p)
  5444. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  5445. returned True and the instruction is still a MOV, thus checking
  5446. the optimisations below }
  5447. { If OptPass2JMP returned False, no optimisations were done to
  5448. the jump and there are no further optimisations that can be done
  5449. to the MOV instruction on this pass }
  5450. end
  5451. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5452. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  5453. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5454. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5455. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5456. { be lazy, checking separately for sub would be slightly better }
  5457. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  5458. begin
  5459. { Change:
  5460. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  5461. addl/q $x,%reg2 subl/q $x,%reg2
  5462. To:
  5463. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  5464. }
  5465. TransferUsedRegs(TmpUsedRegs);
  5466. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5467. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5468. if not GetNextInstruction(hp1, hp2) or
  5469. (
  5470. { The FLAGS register isn't always tracked properly, so do not
  5471. perform this optimisation if a conditional statement follows }
  5472. not RegReadByInstruction(NR_DEFAULTFLAGS, hp2) and
  5473. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)
  5474. ) then
  5475. begin
  5476. reference_reset(NewRef, 1, []);
  5477. NewRef.base := taicpu(p).oper[0]^.reg;
  5478. NewRef.scalefactor := 1;
  5479. if taicpu(hp1).opcode = A_ADD then
  5480. begin
  5481. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  5482. NewRef.offset := taicpu(hp1).oper[0]^.val;
  5483. end
  5484. else
  5485. begin
  5486. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  5487. NewRef.offset := -taicpu(hp1).oper[0]^.val;
  5488. end;
  5489. taicpu(p).opcode := A_LEA;
  5490. taicpu(p).loadref(0, NewRef);
  5491. RemoveInstruction(hp1);
  5492. Result := True;
  5493. Exit;
  5494. end;
  5495. end
  5496. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5497. {$ifdef x86_64}
  5498. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  5499. {$else x86_64}
  5500. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  5501. {$endif x86_64}
  5502. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5503. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  5504. { mov reg1, reg2 mov reg1, reg2
  5505. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  5506. begin
  5507. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5508. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  5509. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  5510. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  5511. TransferUsedRegs(TmpUsedRegs);
  5512. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5513. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  5514. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  5515. then
  5516. begin
  5517. RemoveCurrentP(p, hp1);
  5518. Result:=true;
  5519. end;
  5520. exit;
  5521. end
  5522. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5523. IsXCHGAcceptable and
  5524. { XCHG doesn't support 8-byte registers }
  5525. (taicpu(p).opsize <> S_B) and
  5526. MatchInstruction(hp1, A_MOV, []) and
  5527. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5528. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  5529. GetNextInstruction(hp1, hp2) and
  5530. MatchInstruction(hp2, A_MOV, []) and
  5531. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  5532. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5533. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  5534. begin
  5535. { mov %reg1,%reg2
  5536. mov %reg3,%reg1 -> xchg %reg3,%reg1
  5537. mov %reg2,%reg3
  5538. (%reg2 not used afterwards)
  5539. Note that xchg takes 3 cycles to execute, and generally mov's take
  5540. only one cycle apiece, but the first two mov's can be executed in
  5541. parallel, only taking 2 cycles overall. Older processors should
  5542. therefore only optimise for size. [Kit]
  5543. }
  5544. TransferUsedRegs(TmpUsedRegs);
  5545. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5546. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5547. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  5548. begin
  5549. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  5550. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  5551. taicpu(hp1).opcode := A_XCHG;
  5552. RemoveCurrentP(p, hp1);
  5553. RemoveInstruction(hp2);
  5554. Result := True;
  5555. Exit;
  5556. end;
  5557. end
  5558. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5559. MatchInstruction(hp1, A_SAR, []) then
  5560. begin
  5561. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  5562. begin
  5563. { the use of %edx also covers the opsize being S_L }
  5564. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  5565. begin
  5566. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  5567. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  5568. (taicpu(p).oper[1]^.reg = NR_EDX) then
  5569. begin
  5570. { Change:
  5571. movl %eax,%edx
  5572. sarl $31,%edx
  5573. To:
  5574. cltd
  5575. }
  5576. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  5577. RemoveInstruction(hp1);
  5578. taicpu(p).opcode := A_CDQ;
  5579. taicpu(p).opsize := S_NO;
  5580. taicpu(p).clearop(1);
  5581. taicpu(p).clearop(0);
  5582. taicpu(p).ops:=0;
  5583. Result := True;
  5584. end
  5585. else if (cs_opt_size in current_settings.optimizerswitches) and
  5586. (taicpu(p).oper[0]^.reg = NR_EDX) and
  5587. (taicpu(p).oper[1]^.reg = NR_EAX) then
  5588. begin
  5589. { Change:
  5590. movl %edx,%eax
  5591. sarl $31,%edx
  5592. To:
  5593. movl %edx,%eax
  5594. cltd
  5595. Note that this creates a dependency between the two instructions,
  5596. so only perform if optimising for size.
  5597. }
  5598. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  5599. taicpu(hp1).opcode := A_CDQ;
  5600. taicpu(hp1).opsize := S_NO;
  5601. taicpu(hp1).clearop(1);
  5602. taicpu(hp1).clearop(0);
  5603. taicpu(hp1).ops:=0;
  5604. end;
  5605. {$ifndef x86_64}
  5606. end
  5607. { Don't bother if CMOV is supported, because a more optimal
  5608. sequence would have been generated for the Abs() intrinsic }
  5609. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  5610. { the use of %eax also covers the opsize being S_L }
  5611. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  5612. (taicpu(p).oper[0]^.reg = NR_EAX) and
  5613. (taicpu(p).oper[1]^.reg = NR_EDX) and
  5614. GetNextInstruction(hp1, hp2) and
  5615. MatchInstruction(hp2, A_XOR, [S_L]) and
  5616. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  5617. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  5618. GetNextInstruction(hp2, hp3) and
  5619. MatchInstruction(hp3, A_SUB, [S_L]) and
  5620. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  5621. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  5622. begin
  5623. { Change:
  5624. movl %eax,%edx
  5625. sarl $31,%eax
  5626. xorl %eax,%edx
  5627. subl %eax,%edx
  5628. (Instruction that uses %edx)
  5629. (%eax deallocated)
  5630. (%edx deallocated)
  5631. To:
  5632. cltd
  5633. xorl %edx,%eax <-- Note the registers have swapped
  5634. subl %edx,%eax
  5635. (Instruction that uses %eax) <-- %eax rather than %edx
  5636. }
  5637. TransferUsedRegs(TmpUsedRegs);
  5638. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5639. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5640. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5641. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  5642. begin
  5643. if GetNextInstruction(hp3, hp4) and
  5644. not RegModifiedByInstruction(NR_EDX, hp4) and
  5645. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  5646. begin
  5647. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  5648. taicpu(p).opcode := A_CDQ;
  5649. taicpu(p).clearop(1);
  5650. taicpu(p).clearop(0);
  5651. taicpu(p).ops:=0;
  5652. RemoveInstruction(hp1);
  5653. taicpu(hp2).loadreg(0, NR_EDX);
  5654. taicpu(hp2).loadreg(1, NR_EAX);
  5655. taicpu(hp3).loadreg(0, NR_EDX);
  5656. taicpu(hp3).loadreg(1, NR_EAX);
  5657. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  5658. { Convert references in the following instruction (hp4) from %edx to %eax }
  5659. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  5660. with taicpu(hp4).oper[OperIdx]^ do
  5661. case typ of
  5662. top_reg:
  5663. if getsupreg(reg) = RS_EDX then
  5664. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5665. top_ref:
  5666. begin
  5667. if getsupreg(reg) = RS_EDX then
  5668. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5669. if getsupreg(reg) = RS_EDX then
  5670. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5671. end;
  5672. else
  5673. ;
  5674. end;
  5675. end;
  5676. end;
  5677. {$else x86_64}
  5678. end;
  5679. end
  5680. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  5681. { the use of %rdx also covers the opsize being S_Q }
  5682. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  5683. begin
  5684. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  5685. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  5686. (taicpu(p).oper[1]^.reg = NR_RDX) then
  5687. begin
  5688. { Change:
  5689. movq %rax,%rdx
  5690. sarq $63,%rdx
  5691. To:
  5692. cqto
  5693. }
  5694. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  5695. RemoveInstruction(hp1);
  5696. taicpu(p).opcode := A_CQO;
  5697. taicpu(p).opsize := S_NO;
  5698. taicpu(p).clearop(1);
  5699. taicpu(p).clearop(0);
  5700. taicpu(p).ops:=0;
  5701. Result := True;
  5702. end
  5703. else if (cs_opt_size in current_settings.optimizerswitches) and
  5704. (taicpu(p).oper[0]^.reg = NR_RDX) and
  5705. (taicpu(p).oper[1]^.reg = NR_RAX) then
  5706. begin
  5707. { Change:
  5708. movq %rdx,%rax
  5709. sarq $63,%rdx
  5710. To:
  5711. movq %rdx,%rax
  5712. cqto
  5713. Note that this creates a dependency between the two instructions,
  5714. so only perform if optimising for size.
  5715. }
  5716. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  5717. taicpu(hp1).opcode := A_CQO;
  5718. taicpu(hp1).opsize := S_NO;
  5719. taicpu(hp1).clearop(1);
  5720. taicpu(hp1).clearop(0);
  5721. taicpu(hp1).ops:=0;
  5722. {$endif x86_64}
  5723. end;
  5724. end;
  5725. end
  5726. else if MatchInstruction(hp1, A_MOV, []) and
  5727. (taicpu(hp1).oper[1]^.typ = top_reg) then
  5728. { Though "GetNextInstruction" could be factored out, along with
  5729. the instructions that depend on hp2, it is an expensive call that
  5730. should be delayed for as long as possible, hence we do cheaper
  5731. checks first that are likely to be False. [Kit] }
  5732. begin
  5733. if (
  5734. (
  5735. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  5736. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  5737. (
  5738. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5739. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  5740. )
  5741. ) or
  5742. (
  5743. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  5744. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  5745. (
  5746. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5747. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  5748. )
  5749. )
  5750. ) and
  5751. GetNextInstruction(hp1, hp2) and
  5752. MatchInstruction(hp2, A_SAR, []) and
  5753. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  5754. begin
  5755. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  5756. begin
  5757. { Change:
  5758. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  5759. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  5760. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  5761. To:
  5762. movl r/m,%eax <- Note the change in register
  5763. cltd
  5764. }
  5765. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  5766. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  5767. taicpu(p).loadreg(1, NR_EAX);
  5768. taicpu(hp1).opcode := A_CDQ;
  5769. taicpu(hp1).clearop(1);
  5770. taicpu(hp1).clearop(0);
  5771. taicpu(hp1).ops:=0;
  5772. RemoveInstruction(hp2);
  5773. (*
  5774. {$ifdef x86_64}
  5775. end
  5776. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  5777. { This code sequence does not get generated - however it might become useful
  5778. if and when 128-bit signed integer types make an appearance, so the code
  5779. is kept here for when it is eventually needed. [Kit] }
  5780. (
  5781. (
  5782. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  5783. (
  5784. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5785. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  5786. )
  5787. ) or
  5788. (
  5789. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  5790. (
  5791. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5792. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  5793. )
  5794. )
  5795. ) and
  5796. GetNextInstruction(hp1, hp2) and
  5797. MatchInstruction(hp2, A_SAR, [S_Q]) and
  5798. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  5799. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  5800. begin
  5801. { Change:
  5802. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  5803. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  5804. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  5805. To:
  5806. movq r/m,%rax <- Note the change in register
  5807. cqto
  5808. }
  5809. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  5810. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  5811. taicpu(p).loadreg(1, NR_RAX);
  5812. taicpu(hp1).opcode := A_CQO;
  5813. taicpu(hp1).clearop(1);
  5814. taicpu(hp1).clearop(0);
  5815. taicpu(hp1).ops:=0;
  5816. RemoveInstruction(hp2);
  5817. {$endif x86_64}
  5818. *)
  5819. end;
  5820. end;
  5821. {$ifdef x86_64}
  5822. end
  5823. else if (taicpu(p).opsize = S_L) and
  5824. (taicpu(p).oper[1]^.typ = top_reg) and
  5825. (
  5826. MatchInstruction(hp1, A_MOV,[]) and
  5827. (taicpu(hp1).opsize = S_L) and
  5828. (taicpu(hp1).oper[1]^.typ = top_reg)
  5829. ) and (
  5830. GetNextInstruction(hp1, hp2) and
  5831. (tai(hp2).typ=ait_instruction) and
  5832. (taicpu(hp2).opsize = S_Q) and
  5833. (
  5834. (
  5835. MatchInstruction(hp2, A_ADD,[]) and
  5836. (taicpu(hp2).opsize = S_Q) and
  5837. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  5838. (
  5839. (
  5840. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  5841. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5842. ) or (
  5843. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5844. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  5845. )
  5846. )
  5847. ) or (
  5848. MatchInstruction(hp2, A_LEA,[]) and
  5849. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  5850. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  5851. (
  5852. (
  5853. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  5854. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5855. ) or (
  5856. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5857. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  5858. )
  5859. ) and (
  5860. (
  5861. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5862. ) or (
  5863. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  5864. )
  5865. )
  5866. )
  5867. )
  5868. ) and (
  5869. GetNextInstruction(hp2, hp3) and
  5870. MatchInstruction(hp3, A_SHR,[]) and
  5871. (taicpu(hp3).opsize = S_Q) and
  5872. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  5873. (taicpu(hp3).oper[0]^.val = 1) and
  5874. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  5875. ) then
  5876. begin
  5877. { Change movl x, reg1d movl x, reg1d
  5878. movl y, reg2d movl y, reg2d
  5879. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  5880. shrq $1, reg1q shrq $1, reg1q
  5881. ( reg1d and reg2d can be switched around in the first two instructions )
  5882. To movl x, reg1d
  5883. addl y, reg1d
  5884. rcrl $1, reg1d
  5885. This corresponds to the common expression (x + y) shr 1, where
  5886. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  5887. smaller code, but won't account for x + y causing an overflow). [Kit]
  5888. }
  5889. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  5890. { Change first MOV command to have the same register as the final output }
  5891. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  5892. else
  5893. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  5894. { Change second MOV command to an ADD command. This is easier than
  5895. converting the existing command because it means we don't have to
  5896. touch 'y', which might be a complicated reference, and also the
  5897. fact that the third command might either be ADD or LEA. [Kit] }
  5898. taicpu(hp1).opcode := A_ADD;
  5899. { Delete old ADD/LEA instruction }
  5900. RemoveInstruction(hp2);
  5901. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  5902. taicpu(hp3).opcode := A_RCR;
  5903. taicpu(hp3).changeopsize(S_L);
  5904. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  5905. {$endif x86_64}
  5906. end;
  5907. end;
  5908. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  5909. var
  5910. ThisReg: TRegister;
  5911. MinSize, MaxSize, TrySmaller, TargetSize: TOpSize;
  5912. TargetSubReg: TSubRegister;
  5913. hp1, hp2: tai;
  5914. RegInUse, RegChanged, p_removed: Boolean;
  5915. { Store list of found instructions so we don't have to call
  5916. GetNextInstructionUsingReg multiple times }
  5917. InstrList: array of taicpu;
  5918. InstrMax, Index: Integer;
  5919. UpperLimit, TrySmallerLimit: TCgInt;
  5920. PreMessage: string;
  5921. { Data flow analysis }
  5922. TestValMin, TestValMax: TCgInt;
  5923. SmallerOverflow: Boolean;
  5924. begin
  5925. Result := False;
  5926. p_removed := False;
  5927. { This is anything but quick! }
  5928. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  5929. Exit;
  5930. SetLength(InstrList, 0);
  5931. InstrMax := -1;
  5932. ThisReg := taicpu(p).oper[1]^.reg;
  5933. case taicpu(p).opsize of
  5934. S_BW, S_BL:
  5935. begin
  5936. {$if defined(i386) or defined(i8086)}
  5937. { If the target size is 8-bit, make sure we can actually encode it }
  5938. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  5939. Exit;
  5940. {$endif i386 or i8086}
  5941. UpperLimit := $FF;
  5942. MinSize := S_B;
  5943. if taicpu(p).opsize = S_BW then
  5944. MaxSize := S_W
  5945. else
  5946. MaxSize := S_L;
  5947. end;
  5948. S_WL:
  5949. begin
  5950. UpperLimit := $FFFF;
  5951. MinSize := S_W;
  5952. MaxSize := S_L;
  5953. end
  5954. else
  5955. InternalError(2020112301);
  5956. end;
  5957. TestValMin := 0;
  5958. TestValMax := UpperLimit;
  5959. TrySmallerLimit := UpperLimit;
  5960. TrySmaller := S_NO;
  5961. SmallerOverflow := False;
  5962. RegChanged := False;
  5963. hp1 := p;
  5964. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  5965. (hp1.typ = ait_instruction) and
  5966. (
  5967. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  5968. instruction that doesn't actually contain ThisReg }
  5969. (cs_opt_level3 in current_settings.optimizerswitches) or
  5970. RegInInstruction(ThisReg, hp1)
  5971. ) do
  5972. begin
  5973. case taicpu(hp1).opcode of
  5974. A_INC,A_DEC:
  5975. begin
  5976. { Has to be an exact match on the register }
  5977. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  5978. Break;
  5979. if taicpu(hp1).opcode = A_INC then
  5980. begin
  5981. Inc(TestValMin);
  5982. Inc(TestValMax);
  5983. end
  5984. else
  5985. begin
  5986. Dec(TestValMin);
  5987. Dec(TestValMax);
  5988. end;
  5989. end;
  5990. A_CMP:
  5991. begin
  5992. if (taicpu(hp1).oper[1]^.typ <> top_reg) or
  5993. { Has to be an exact match on the register }
  5994. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  5995. (taicpu(hp1).oper[0]^.typ <> top_const) or
  5996. { Make sure the comparison value is not smaller than the
  5997. smallest allowed signed value for the minimum size (e.g.
  5998. -128 for 8-bit) }
  5999. not (
  6000. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6001. { Is it in the negative range? }
  6002. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6003. ) then
  6004. Break;
  6005. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6006. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6007. if (TestValMin < TrySmallerLimit) or (TestValMax < TrySmallerLimit) or
  6008. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6009. { Overflow }
  6010. Break;
  6011. { Check to see if the active register is used afterwards }
  6012. TransferUsedRegs(TmpUsedRegs);
  6013. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  6014. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6015. begin
  6016. case MinSize of
  6017. S_B:
  6018. TargetSubReg := R_SUBL;
  6019. S_W:
  6020. TargetSubReg := R_SUBW;
  6021. else
  6022. InternalError(2021051002);
  6023. end;
  6024. { Update the register to its new size }
  6025. setsubreg(ThisReg, TargetSubReg);
  6026. taicpu(hp1).oper[1]^.reg := ThisReg;
  6027. taicpu(hp1).opsize := MinSize;
  6028. { Convert the input MOVZX to a MOV }
  6029. if (taicpu(p).oper[0]^.typ = top_reg) and
  6030. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6031. begin
  6032. { Or remove it completely! }
  6033. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  6034. RemoveCurrentP(p);
  6035. p_removed := True;
  6036. end
  6037. else
  6038. begin
  6039. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  6040. taicpu(p).opcode := A_MOV;
  6041. taicpu(p).oper[1]^.reg := ThisReg;
  6042. taicpu(p).opsize := MinSize;
  6043. end;
  6044. if (InstrMax >= 0) then
  6045. begin
  6046. for Index := 0 to InstrMax do
  6047. begin
  6048. { If p_removed is true, then the original MOV/Z was removed
  6049. and removing the AND instruction may not be safe if it
  6050. appears first }
  6051. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6052. InternalError(2020112311);
  6053. if InstrList[Index].oper[0]^.typ = top_reg then
  6054. InstrList[Index].oper[0]^.reg := ThisReg;
  6055. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6056. InstrList[Index].opsize := MinSize;
  6057. end;
  6058. end;
  6059. Result := True;
  6060. Exit;
  6061. end;
  6062. end;
  6063. { OR and XOR are not included because they can too easily fool
  6064. the data flow analysis (they can cause non-linear behaviour) }
  6065. A_ADD,A_SUB,A_AND,A_SHL,A_SHR:
  6066. begin
  6067. if
  6068. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6069. { Has to be an exact match on the register }
  6070. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  6071. (
  6072. (
  6073. (taicpu(hp1).oper[0]^.typ = top_const) and
  6074. (
  6075. (
  6076. (taicpu(hp1).opcode = A_SHL) and
  6077. (
  6078. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  6079. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  6080. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  6081. )
  6082. ) or (
  6083. (taicpu(hp1).opcode <> A_SHL) and
  6084. (
  6085. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6086. { Is it in the negative range? }
  6087. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6088. )
  6089. )
  6090. )
  6091. ) or (
  6092. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  6093. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  6094. )
  6095. ) then
  6096. Break;
  6097. case taicpu(hp1).opcode of
  6098. A_ADD:
  6099. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6100. begin
  6101. TestValMin := TestValMin * 2;
  6102. TestValMax := TestValMax * 2;
  6103. end
  6104. else
  6105. begin
  6106. TestValMin := TestValMin + taicpu(hp1).oper[0]^.val;
  6107. TestValMax := TestValMax + taicpu(hp1).oper[0]^.val;
  6108. end;
  6109. A_SUB:
  6110. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6111. begin
  6112. TestValMin := 0;
  6113. TestValMax := 0;
  6114. end
  6115. else
  6116. begin
  6117. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6118. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6119. end;
  6120. A_AND:
  6121. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6122. begin
  6123. { we might be able to go smaller if AND appears first }
  6124. if InstrMax = -1 then
  6125. case MinSize of
  6126. S_B:
  6127. ;
  6128. S_W:
  6129. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6130. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6131. begin
  6132. TrySmaller := S_B;
  6133. TrySmallerLimit := $FF;
  6134. end;
  6135. S_L:
  6136. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6137. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6138. begin
  6139. TrySmaller := S_B;
  6140. TrySmallerLimit := $FF;
  6141. end
  6142. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  6143. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  6144. begin
  6145. TrySmaller := S_W;
  6146. TrySmallerLimit := $FFFF;
  6147. end;
  6148. else
  6149. InternalError(2020112320);
  6150. end;
  6151. TestValMin := TestValMin and taicpu(hp1).oper[0]^.val;
  6152. TestValMax := TestValMax and taicpu(hp1).oper[0]^.val;
  6153. end;
  6154. A_SHL:
  6155. begin
  6156. TestValMin := TestValMin shl taicpu(hp1).oper[0]^.val;
  6157. TestValMax := TestValMax shl taicpu(hp1).oper[0]^.val;
  6158. end;
  6159. A_SHR:
  6160. begin
  6161. { we might be able to go smaller if SHR appears first }
  6162. if InstrMax = -1 then
  6163. case MinSize of
  6164. S_B:
  6165. ;
  6166. S_W:
  6167. if (taicpu(hp1).oper[0]^.val >= 8) then
  6168. begin
  6169. TrySmaller := S_B;
  6170. TrySmallerLimit := $FF;
  6171. end;
  6172. S_L:
  6173. if (taicpu(hp1).oper[0]^.val >= 24) then
  6174. begin
  6175. TrySmaller := S_B;
  6176. TrySmallerLimit := $FF;
  6177. end
  6178. else if (taicpu(hp1).oper[0]^.val >= 16) then
  6179. begin
  6180. TrySmaller := S_W;
  6181. TrySmallerLimit := $FFFF;
  6182. end;
  6183. else
  6184. InternalError(2020112321);
  6185. end;
  6186. TestValMin := TestValMin shr taicpu(hp1).oper[0]^.val;
  6187. TestValMax := TestValMax shr taicpu(hp1).oper[0]^.val;
  6188. end;
  6189. else
  6190. InternalError(2020112303);
  6191. end;
  6192. end;
  6193. (*
  6194. A_IMUL:
  6195. case taicpu(hp1).ops of
  6196. 2:
  6197. begin
  6198. if not MatchOpType(hp1, top_reg, top_reg) or
  6199. { Has to be an exact match on the register }
  6200. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  6201. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  6202. Break;
  6203. TestValMin := TestValMin * TestValMin;
  6204. TestValMax := TestValMax * TestValMax;
  6205. end;
  6206. 3:
  6207. begin
  6208. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6209. { Has to be an exact match on the register }
  6210. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6211. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6212. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6213. { Is it in the negative range? }
  6214. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6215. Break;
  6216. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  6217. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  6218. end;
  6219. else
  6220. Break;
  6221. end;
  6222. A_IDIV:
  6223. case taicpu(hp1).ops of
  6224. 3:
  6225. begin
  6226. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6227. { Has to be an exact match on the register }
  6228. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6229. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6230. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6231. { Is it in the negative range? }
  6232. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6233. Break;
  6234. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  6235. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  6236. end;
  6237. else
  6238. Break;
  6239. end;
  6240. *)
  6241. A_MOVZX:
  6242. begin
  6243. if not MatchOpType(taicpu(hp1), top_reg, top_reg) then
  6244. Break;
  6245. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  6246. begin
  6247. { Because hp1 was obtained via GetNextInstructionUsingReg
  6248. and ThisReg doesn't appear in the first operand, it
  6249. must appear in the second operand and hence gets
  6250. overwritten }
  6251. if (InstrMax = -1) and
  6252. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6253. begin
  6254. { The two MOVZX instructions are adjacent, so remove the first one }
  6255. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  6256. RemoveCurrentP(p);
  6257. Result := True;
  6258. Exit;
  6259. end;
  6260. Break;
  6261. end;
  6262. { The objective here is to try to find a combination that
  6263. removes one of the MOV/Z instructions. }
  6264. case taicpu(hp1).opsize of
  6265. S_WL:
  6266. if (MinSize in [S_B, S_W]) then
  6267. begin
  6268. TargetSize := S_L;
  6269. TargetSubReg := R_SUBD;
  6270. end
  6271. else if ((TrySmaller in [S_B, S_W]) and not SmallerOverflow) then
  6272. begin
  6273. TargetSize := TrySmaller;
  6274. if TrySmaller = S_B then
  6275. TargetSubReg := R_SUBL
  6276. else
  6277. TargetSubReg := R_SUBW;
  6278. end
  6279. else
  6280. Break;
  6281. S_BW:
  6282. if (MinSize in [S_B, S_W]) then
  6283. begin
  6284. TargetSize := S_W;
  6285. TargetSubReg := R_SUBW;
  6286. end
  6287. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6288. begin
  6289. TargetSize := S_B;
  6290. TargetSubReg := R_SUBL;
  6291. end
  6292. else
  6293. Break;
  6294. S_BL:
  6295. if (MinSize in [S_B, S_W]) then
  6296. begin
  6297. TargetSize := S_L;
  6298. TargetSubReg := R_SUBD;
  6299. end
  6300. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6301. begin
  6302. TargetSize := S_B;
  6303. TargetSubReg := R_SUBL;
  6304. end
  6305. else
  6306. Break;
  6307. else
  6308. InternalError(2020112302);
  6309. end;
  6310. { Update the register to its new size }
  6311. setsubreg(ThisReg, TargetSubReg);
  6312. if TargetSize = MinSize then
  6313. begin
  6314. { Convert the input MOVZX to a MOV }
  6315. if (taicpu(p).oper[0]^.typ = top_reg) and
  6316. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6317. begin
  6318. { Or remove it completely! }
  6319. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  6320. RemoveCurrentP(p);
  6321. p_removed := True;
  6322. end
  6323. else
  6324. begin
  6325. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  6326. taicpu(p).opcode := A_MOV;
  6327. taicpu(p).oper[1]^.reg := ThisReg;
  6328. taicpu(p).opsize := TargetSize;
  6329. end;
  6330. Result := True;
  6331. end
  6332. else if TargetSize <> MaxSize then
  6333. begin
  6334. case MaxSize of
  6335. S_L:
  6336. if TargetSize = S_W then
  6337. begin
  6338. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  6339. taicpu(p).opsize := S_BW;
  6340. taicpu(p).oper[1]^.reg := ThisReg;
  6341. Result := True;
  6342. end
  6343. else
  6344. InternalError(2020112341);
  6345. S_W:
  6346. if TargetSize = S_L then
  6347. begin
  6348. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  6349. taicpu(p).opsize := S_BL;
  6350. taicpu(p).oper[1]^.reg := ThisReg;
  6351. Result := True;
  6352. end
  6353. else
  6354. InternalError(2020112342);
  6355. else
  6356. ;
  6357. end;
  6358. end;
  6359. if (MaxSize = TargetSize) or
  6360. ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  6361. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  6362. begin
  6363. { Convert the output MOVZX to a MOV }
  6364. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6365. begin
  6366. { Or remove it completely! }
  6367. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  6368. { Be careful; if p = hp1 and p was also removed, p
  6369. will become a dangling pointer }
  6370. if p = hp1 then
  6371. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6372. else
  6373. RemoveInstruction(hp1);
  6374. end
  6375. else
  6376. begin
  6377. taicpu(hp1).opcode := A_MOV;
  6378. taicpu(hp1).oper[0]^.reg := ThisReg;
  6379. taicpu(hp1).opsize := TargetSize;
  6380. { Check to see if the active register is used afterwards;
  6381. if not, we can change it and make a saving. }
  6382. RegInUse := False;
  6383. TransferUsedRegs(TmpUsedRegs);
  6384. { The target register may be marked as in use to cross
  6385. a jump to a distant label, so exclude it }
  6386. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  6387. hp2 := p;
  6388. repeat
  6389. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6390. { Explicitly check for the excluded register (don't include the first
  6391. instruction as it may be reading from here }
  6392. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  6393. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  6394. begin
  6395. RegInUse := True;
  6396. Break;
  6397. end;
  6398. if not GetNextInstruction(hp2, hp2) then
  6399. InternalError(2020112340);
  6400. until (hp2 = hp1);
  6401. if not RegInUse and not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6402. begin
  6403. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  6404. ThisReg := taicpu(hp1).oper[1]^.reg;
  6405. RegChanged := True;
  6406. TransferUsedRegs(TmpUsedRegs);
  6407. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  6408. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  6409. if p = hp1 then
  6410. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6411. else
  6412. RemoveInstruction(hp1);
  6413. { Instruction will become "mov %reg,%reg" }
  6414. if not p_removed and (taicpu(p).opcode = A_MOV) and
  6415. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  6416. begin
  6417. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  6418. RemoveCurrentP(p);
  6419. p_removed := True;
  6420. end
  6421. else
  6422. taicpu(p).oper[1]^.reg := ThisReg;
  6423. Result := True;
  6424. end
  6425. else
  6426. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  6427. end;
  6428. end
  6429. else
  6430. InternalError(2020112330);
  6431. { Now go through every instruction we found and change the
  6432. size. If TargetSize = MaxSize, then almost no changes are
  6433. needed and Result can remain False if it hasn't been set
  6434. yet.
  6435. If RegChanged is True, then the register requires changing
  6436. and so the point about TargetSize = MaxSize doesn't apply. }
  6437. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  6438. begin
  6439. for Index := 0 to InstrMax do
  6440. begin
  6441. { If p_removed is true, then the original MOV/Z was removed
  6442. and removing the AND instruction may not be safe if it
  6443. appears first }
  6444. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6445. InternalError(2020112310);
  6446. if InstrList[Index].oper[0]^.typ = top_reg then
  6447. InstrList[Index].oper[0]^.reg := ThisReg;
  6448. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6449. InstrList[Index].opsize := TargetSize;
  6450. end;
  6451. Result := True;
  6452. end;
  6453. Exit;
  6454. end;
  6455. else
  6456. { This includes ADC, SBB, IDIV and SAR }
  6457. Break;
  6458. end;
  6459. if (TestValMin < 0) or (TestValMax < 0) or
  6460. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6461. { Overflow }
  6462. Break
  6463. else if not SmallerOverflow and (TrySmaller <> S_NO) and
  6464. ((TestValMin > TrySmallerLimit) or (TestValMax > TrySmallerLimit)) then
  6465. SmallerOverflow := True;
  6466. { Contains highest index (so instruction count - 1) }
  6467. Inc(InstrMax);
  6468. if InstrMax > High(InstrList) then
  6469. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6470. InstrList[InstrMax] := taicpu(hp1);
  6471. end;
  6472. end;
  6473. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  6474. var
  6475. hp1 : tai;
  6476. begin
  6477. Result:=false;
  6478. if (taicpu(p).ops >= 2) and
  6479. ((taicpu(p).oper[0]^.typ = top_const) or
  6480. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  6481. (taicpu(p).oper[1]^.typ = top_reg) and
  6482. ((taicpu(p).ops = 2) or
  6483. ((taicpu(p).oper[2]^.typ = top_reg) and
  6484. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  6485. GetLastInstruction(p,hp1) and
  6486. MatchInstruction(hp1,A_MOV,[]) and
  6487. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6488. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6489. begin
  6490. TransferUsedRegs(TmpUsedRegs);
  6491. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  6492. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  6493. { change
  6494. mov reg1,reg2
  6495. imul y,reg2 to imul y,reg1,reg2 }
  6496. begin
  6497. taicpu(p).ops := 3;
  6498. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  6499. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6500. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  6501. RemoveInstruction(hp1);
  6502. result:=true;
  6503. end;
  6504. end;
  6505. end;
  6506. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  6507. var
  6508. ThisLabel: TAsmLabel;
  6509. begin
  6510. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  6511. ThisLabel.decrefs;
  6512. taicpu(p).opcode := A_RET;
  6513. taicpu(p).is_jmp := false;
  6514. taicpu(p).ops := taicpu(ret_p).ops;
  6515. case taicpu(ret_p).ops of
  6516. 0:
  6517. taicpu(p).clearop(0);
  6518. 1:
  6519. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  6520. else
  6521. internalerror(2016041301);
  6522. end;
  6523. { If the original label is now dead, it might turn out that the label
  6524. immediately follows p. As a result, everything beyond it, which will
  6525. be just some final register configuration and a RET instruction, is
  6526. now dead code. [Kit] }
  6527. { NOTE: This is much faster than introducing a OptPass2RET routine and
  6528. running RemoveDeadCodeAfterJump for each RET instruction, because
  6529. this optimisation rarely happens and most RETs appear at the end of
  6530. routines where there is nothing that can be stripped. [Kit] }
  6531. if not ThisLabel.is_used then
  6532. RemoveDeadCodeAfterJump(p);
  6533. end;
  6534. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  6535. var
  6536. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  6537. Unconditional, PotentialModified: Boolean;
  6538. OperPtr: POper;
  6539. NewRef: TReference;
  6540. InstrList: array of taicpu;
  6541. InstrMax, Index: Integer;
  6542. const
  6543. {$ifdef DEBUG_AOPTCPU}
  6544. SNoFlags: shortstring = ' so the flags aren''t modified';
  6545. {$else DEBUG_AOPTCPU}
  6546. SNoFlags = '';
  6547. {$endif DEBUG_AOPTCPU}
  6548. begin
  6549. Result:=false;
  6550. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  6551. begin
  6552. if MatchInstruction(hp1, A_TEST, [S_B]) and
  6553. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6554. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6555. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6556. GetNextInstruction(hp1, hp2) and
  6557. MatchInstruction(hp2, A_Jcc, []) then
  6558. { Change from: To:
  6559. set(C) %reg j(~C) label
  6560. test %reg,%reg/cmp $0,%reg
  6561. je label
  6562. set(C) %reg j(C) label
  6563. test %reg,%reg/cmp $0,%reg
  6564. jne label
  6565. }
  6566. begin
  6567. { Before we do anything else, we need to check the instructions
  6568. in between SETcc and TEST to make sure they don't modify the
  6569. FLAGS register - if -O2 or under, there won't be any
  6570. instructions between SET and TEST }
  6571. TransferUsedRegs(TmpUsedRegs);
  6572. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6573. if (cs_opt_level3 in current_settings.optimizerswitches) then
  6574. begin
  6575. next := p;
  6576. SetLength(InstrList, 0);
  6577. InstrMax := -1;
  6578. PotentialModified := False;
  6579. { Make a note of every instruction that modifies the FLAGS
  6580. register }
  6581. while GetNextInstruction(next, next) and (next <> hp1) do
  6582. begin
  6583. if next.typ <> ait_instruction then
  6584. { GetNextInstructionUsingReg should have returned False }
  6585. InternalError(2021051701);
  6586. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  6587. begin
  6588. case taicpu(next).opcode of
  6589. A_SETcc,
  6590. A_CMOVcc,
  6591. A_Jcc:
  6592. begin
  6593. if PotentialModified then
  6594. { Not safe because the flags were modified earlier }
  6595. Exit
  6596. else
  6597. { Condition is the same as the initial SETcc, so this is safe
  6598. (don't add to instruction list though) }
  6599. Continue;
  6600. end;
  6601. A_ADD:
  6602. begin
  6603. if (taicpu(next).opsize = S_B) or
  6604. { LEA doesn't support 8-bit operands }
  6605. (taicpu(next).oper[1]^.typ <> top_reg) or
  6606. { Must write to a register }
  6607. (taicpu(next).oper[0]^.typ = top_ref) then
  6608. { Require a constant or a register }
  6609. Exit;
  6610. PotentialModified := True;
  6611. end;
  6612. A_SUB:
  6613. begin
  6614. if (taicpu(next).opsize = S_B) or
  6615. { LEA doesn't support 8-bit operands }
  6616. (taicpu(next).oper[1]^.typ <> top_reg) or
  6617. { Must write to a register }
  6618. (taicpu(next).oper[0]^.typ <> top_const) or
  6619. (taicpu(next).oper[0]^.val = $80000000) then
  6620. { Can't subtract a register with LEA - also
  6621. check that the value isn't -2^31, as this
  6622. can't be negated }
  6623. Exit;
  6624. PotentialModified := True;
  6625. end;
  6626. A_SAL,
  6627. A_SHL:
  6628. begin
  6629. if (taicpu(next).opsize = S_B) or
  6630. { LEA doesn't support 8-bit operands }
  6631. (taicpu(next).oper[1]^.typ <> top_reg) or
  6632. { Must write to a register }
  6633. (taicpu(next).oper[0]^.typ <> top_const) or
  6634. (taicpu(next).oper[0]^.val < 0) or
  6635. (taicpu(next).oper[0]^.val > 3) then
  6636. Exit;
  6637. PotentialModified := True;
  6638. end;
  6639. A_IMUL:
  6640. begin
  6641. if (taicpu(next).ops <> 3) or
  6642. (taicpu(next).oper[1]^.typ <> top_reg) or
  6643. { Must write to a register }
  6644. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  6645. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  6646. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  6647. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  6648. Exit
  6649. else
  6650. PotentialModified := True;
  6651. end;
  6652. else
  6653. { Don't know how to change this, so abort }
  6654. Exit;
  6655. end;
  6656. { Contains highest index (so instruction count - 1) }
  6657. Inc(InstrMax);
  6658. if InstrMax > High(InstrList) then
  6659. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6660. InstrList[InstrMax] := taicpu(next);
  6661. end;
  6662. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  6663. end;
  6664. if not Assigned(next) or (next <> hp1) then
  6665. { It should be equal to hp1 }
  6666. InternalError(2021051702);
  6667. { Cycle through each instruction and check to see if we can
  6668. change them to versions that don't modify the flags }
  6669. if (InstrMax >= 0) then
  6670. begin
  6671. for Index := 0 to InstrMax do
  6672. case InstrList[Index].opcode of
  6673. A_ADD:
  6674. begin
  6675. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  6676. InstrList[Index].opcode := A_LEA;
  6677. reference_reset(NewRef, 1, []);
  6678. NewRef.base := InstrList[Index].oper[1]^.reg;
  6679. if InstrList[Index].oper[0]^.typ = top_reg then
  6680. begin
  6681. NewRef.index := InstrList[Index].oper[0]^.reg;
  6682. NewRef.scalefactor := 1;
  6683. end
  6684. else
  6685. NewRef.offset := InstrList[Index].oper[0]^.val;
  6686. InstrList[Index].loadref(0, NewRef);
  6687. end;
  6688. A_SUB:
  6689. begin
  6690. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  6691. InstrList[Index].opcode := A_LEA;
  6692. reference_reset(NewRef, 1, []);
  6693. NewRef.base := InstrList[Index].oper[1]^.reg;
  6694. NewRef.offset := -InstrList[Index].oper[0]^.val;
  6695. InstrList[Index].loadref(0, NewRef);
  6696. end;
  6697. A_SHL,
  6698. A_SAL:
  6699. begin
  6700. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  6701. InstrList[Index].opcode := A_LEA;
  6702. reference_reset(NewRef, 1, []);
  6703. NewRef.index := InstrList[Index].oper[1]^.reg;
  6704. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  6705. InstrList[Index].loadref(0, NewRef);
  6706. end;
  6707. A_IMUL:
  6708. begin
  6709. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  6710. InstrList[Index].opcode := A_LEA;
  6711. reference_reset(NewRef, 1, []);
  6712. NewRef.index := InstrList[Index].oper[1]^.reg;
  6713. case InstrList[Index].oper[0]^.val of
  6714. 2, 4, 8:
  6715. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  6716. else {3, 5 and 9}
  6717. begin
  6718. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  6719. NewRef.base := InstrList[Index].oper[1]^.reg;
  6720. end;
  6721. end;
  6722. InstrList[Index].loadref(0, NewRef);
  6723. end;
  6724. else
  6725. InternalError(2021051710);
  6726. end;
  6727. end;
  6728. { Mark the FLAGS register as used across this whole block }
  6729. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  6730. end;
  6731. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6732. JumpC := taicpu(hp2).condition;
  6733. Unconditional := False;
  6734. if conditions_equal(JumpC, C_E) then
  6735. SetC := inverse_cond(taicpu(p).condition)
  6736. else if conditions_equal(JumpC, C_NE) then
  6737. SetC := taicpu(p).condition
  6738. else
  6739. { We've got something weird here (and inefficent) }
  6740. begin
  6741. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  6742. SetC := C_NONE;
  6743. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  6744. if condition_in(C_AE, JumpC) then
  6745. Unconditional := True
  6746. else
  6747. { Not sure what to do with this jump - drop out }
  6748. Exit;
  6749. end;
  6750. RemoveInstruction(hp1);
  6751. if Unconditional then
  6752. MakeUnconditional(taicpu(hp2))
  6753. else
  6754. begin
  6755. if SetC = C_NONE then
  6756. InternalError(2018061402);
  6757. taicpu(hp2).SetCondition(SetC);
  6758. end;
  6759. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  6760. TmpUsedRegs }
  6761. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  6762. begin
  6763. RemoveCurrentp(p, hp2);
  6764. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  6765. end
  6766. else
  6767. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  6768. Result := True;
  6769. end
  6770. else if
  6771. { Make sure the instructions are adjacent }
  6772. (
  6773. not (cs_opt_level3 in current_settings.optimizerswitches) or
  6774. GetNextInstruction(p, hp1)
  6775. ) and
  6776. MatchInstruction(hp1, A_MOV, [S_B]) and
  6777. { Writing to memory is allowed }
  6778. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  6779. begin
  6780. {
  6781. Watch out for sequences such as:
  6782. set(c)b %regb
  6783. movb %regb,(ref)
  6784. movb $0,1(ref)
  6785. movb $0,2(ref)
  6786. movb $0,3(ref)
  6787. Much more efficient to turn it into:
  6788. movl $0,%regl
  6789. set(c)b %regb
  6790. movl %regl,(ref)
  6791. Or:
  6792. set(c)b %regb
  6793. movzbl %regb,%regl
  6794. movl %regl,(ref)
  6795. }
  6796. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  6797. GetNextInstruction(hp1, hp2) and
  6798. MatchInstruction(hp2, A_MOV, [S_B]) and
  6799. (taicpu(hp2).oper[1]^.typ = top_ref) and
  6800. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  6801. begin
  6802. { Don't do anything else except set Result to True }
  6803. end
  6804. else
  6805. begin
  6806. if taicpu(p).oper[0]^.typ = top_reg then
  6807. begin
  6808. TransferUsedRegs(TmpUsedRegs);
  6809. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6810. end;
  6811. { If it's not a register, it's a memory address }
  6812. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  6813. begin
  6814. { Even if the register is still in use, we can minimise the
  6815. pipeline stall by changing the MOV into another SETcc. }
  6816. taicpu(hp1).opcode := A_SETcc;
  6817. taicpu(hp1).condition := taicpu(p).condition;
  6818. if taicpu(hp1).oper[1]^.typ = top_ref then
  6819. begin
  6820. { Swapping the operand pointers like this is probably a
  6821. bit naughty, but it is far faster than using loadoper
  6822. to transfer the reference from oper[1] to oper[0] if
  6823. you take into account the extra procedure calls and
  6824. the memory allocation and deallocation required }
  6825. OperPtr := taicpu(hp1).oper[1];
  6826. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  6827. taicpu(hp1).oper[0] := OperPtr;
  6828. end
  6829. else
  6830. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  6831. taicpu(hp1).clearop(1);
  6832. taicpu(hp1).ops := 1;
  6833. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  6834. end
  6835. else
  6836. begin
  6837. if taicpu(hp1).oper[1]^.typ = top_reg then
  6838. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  6839. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6840. RemoveInstruction(hp1);
  6841. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  6842. end
  6843. end;
  6844. Result := True;
  6845. end;
  6846. end;
  6847. end;
  6848. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  6849. var
  6850. hp1: tai;
  6851. Count: Integer;
  6852. OrigLabel: TAsmLabel;
  6853. begin
  6854. result := False;
  6855. { Sometimes, the optimisations below can permit this }
  6856. RemoveDeadCodeAfterJump(p);
  6857. 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
  6858. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  6859. begin
  6860. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6861. { Also a side-effect of optimisations }
  6862. if CollapseZeroDistJump(p, OrigLabel) then
  6863. begin
  6864. Result := True;
  6865. Exit;
  6866. end;
  6867. hp1 := GetLabelWithSym(OrigLabel);
  6868. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  6869. begin
  6870. case taicpu(hp1).opcode of
  6871. A_RET:
  6872. {
  6873. change
  6874. jmp .L1
  6875. ...
  6876. .L1:
  6877. ret
  6878. into
  6879. ret
  6880. }
  6881. begin
  6882. ConvertJumpToRET(p, hp1);
  6883. result:=true;
  6884. end;
  6885. { Check any kind of direct assignment instruction }
  6886. A_MOV,
  6887. A_MOVD,
  6888. A_MOVQ,
  6889. A_MOVSX,
  6890. {$ifdef x86_64}
  6891. A_MOVSXD,
  6892. {$endif x86_64}
  6893. A_MOVZX,
  6894. A_MOVAPS,
  6895. A_MOVUPS,
  6896. A_MOVSD,
  6897. A_MOVAPD,
  6898. A_MOVUPD,
  6899. A_MOVDQA,
  6900. A_MOVDQU,
  6901. A_VMOVSS,
  6902. A_VMOVAPS,
  6903. A_VMOVUPS,
  6904. A_VMOVSD,
  6905. A_VMOVAPD,
  6906. A_VMOVUPD,
  6907. A_VMOVDQA,
  6908. A_VMOVDQU:
  6909. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  6910. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  6911. begin
  6912. Result := True;
  6913. Exit;
  6914. end;
  6915. else
  6916. ;
  6917. end;
  6918. end;
  6919. end;
  6920. end;
  6921. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  6922. begin
  6923. CanBeCMOV:=assigned(p) and
  6924. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  6925. { we can't use cmov ref,reg because
  6926. ref could be nil and cmov still throws an exception
  6927. if ref=nil but the mov isn't done (FK)
  6928. or ((taicpu(p).oper[0]^.typ = top_ref) and
  6929. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  6930. }
  6931. (taicpu(p).oper[1]^.typ = top_reg) and
  6932. (
  6933. (taicpu(p).oper[0]^.typ = top_reg) or
  6934. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  6935. it is not expected that this can cause a seg. violation }
  6936. (
  6937. (taicpu(p).oper[0]^.typ = top_ref) and
  6938. IsRefSafe(taicpu(p).oper[0]^.ref)
  6939. )
  6940. );
  6941. end;
  6942. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  6943. var
  6944. hp1,hp2: tai;
  6945. {$ifndef i8086}
  6946. hp3,hp4,hpmov2, hp5: tai;
  6947. l : Longint;
  6948. condition : TAsmCond;
  6949. {$endif i8086}
  6950. carryadd_opcode : TAsmOp;
  6951. symbol: TAsmSymbol;
  6952. reg: tsuperregister;
  6953. increg, tmpreg: TRegister;
  6954. begin
  6955. result:=false;
  6956. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  6957. begin
  6958. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6959. if (
  6960. (
  6961. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  6962. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  6963. (Taicpu(hp1).oper[0]^.val=1)
  6964. ) or
  6965. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  6966. ) and
  6967. GetNextInstruction(hp1,hp2) and
  6968. SkipAligns(hp2, hp2) and
  6969. (hp2.typ = ait_label) and
  6970. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  6971. { jb @@1 cmc
  6972. inc/dec operand --> adc/sbb operand,0
  6973. @@1:
  6974. ... and ...
  6975. jnb @@1
  6976. inc/dec operand --> adc/sbb operand,0
  6977. @@1: }
  6978. begin
  6979. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  6980. begin
  6981. case taicpu(hp1).opcode of
  6982. A_INC,
  6983. A_ADD:
  6984. carryadd_opcode:=A_ADC;
  6985. A_DEC,
  6986. A_SUB:
  6987. carryadd_opcode:=A_SBB;
  6988. else
  6989. InternalError(2021011001);
  6990. end;
  6991. Taicpu(p).clearop(0);
  6992. Taicpu(p).ops:=0;
  6993. Taicpu(p).is_jmp:=false;
  6994. Taicpu(p).opcode:=A_CMC;
  6995. Taicpu(p).condition:=C_NONE;
  6996. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  6997. Taicpu(hp1).ops:=2;
  6998. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  6999. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7000. else
  7001. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7002. Taicpu(hp1).loadconst(0,0);
  7003. Taicpu(hp1).opcode:=carryadd_opcode;
  7004. result:=true;
  7005. exit;
  7006. end
  7007. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  7008. begin
  7009. case taicpu(hp1).opcode of
  7010. A_INC,
  7011. A_ADD:
  7012. carryadd_opcode:=A_ADC;
  7013. A_DEC,
  7014. A_SUB:
  7015. carryadd_opcode:=A_SBB;
  7016. else
  7017. InternalError(2021011002);
  7018. end;
  7019. Taicpu(hp1).ops:=2;
  7020. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  7021. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  7022. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7023. else
  7024. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7025. Taicpu(hp1).loadconst(0,0);
  7026. Taicpu(hp1).opcode:=carryadd_opcode;
  7027. RemoveCurrentP(p, hp1);
  7028. result:=true;
  7029. exit;
  7030. end
  7031. {
  7032. jcc @@1 setcc tmpreg
  7033. inc/dec/add/sub operand -> (movzx tmpreg)
  7034. @@1: add/sub tmpreg,operand
  7035. While this increases code size slightly, it makes the code much faster if the
  7036. jump is unpredictable
  7037. }
  7038. else if not(cs_opt_size in current_settings.optimizerswitches) then
  7039. begin
  7040. { search for an available register which is volatile }
  7041. for reg in tcpuregisterset do
  7042. begin
  7043. if
  7044. {$if defined(i386) or defined(i8086)}
  7045. { Only use registers whose lowest 8-bits can Be accessed }
  7046. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  7047. {$endif i386 or i8086}
  7048. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  7049. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  7050. { We don't need to check if tmpreg is in hp1 or not, because
  7051. it will be marked as in use at p (if not, this is
  7052. indictive of a compiler bug). }
  7053. then
  7054. begin
  7055. TAsmLabel(symbol).decrefs;
  7056. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  7057. Taicpu(p).clearop(0);
  7058. Taicpu(p).ops:=1;
  7059. Taicpu(p).is_jmp:=false;
  7060. Taicpu(p).opcode:=A_SETcc;
  7061. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  7062. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  7063. Taicpu(p).loadreg(0,increg);
  7064. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  7065. begin
  7066. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  7067. R_SUBW:
  7068. begin
  7069. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  7070. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  7071. end;
  7072. R_SUBD:
  7073. begin
  7074. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  7075. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  7076. end;
  7077. {$ifdef x86_64}
  7078. R_SUBQ:
  7079. begin
  7080. { MOVZX doesn't have a 64-bit variant, because
  7081. the 32-bit version implicitly zeroes the
  7082. upper 32-bits of the destination register }
  7083. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  7084. newreg(R_INTREGISTER,reg,R_SUBD));
  7085. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  7086. end;
  7087. {$endif x86_64}
  7088. else
  7089. Internalerror(2020030601);
  7090. end;
  7091. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  7092. asml.InsertAfter(hp2,p);
  7093. end
  7094. else
  7095. tmpreg := increg;
  7096. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  7097. begin
  7098. Taicpu(hp1).ops:=2;
  7099. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  7100. end;
  7101. Taicpu(hp1).loadreg(0,tmpreg);
  7102. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  7103. Result := True;
  7104. { p is no longer a Jcc instruction, so exit }
  7105. Exit;
  7106. end;
  7107. end;
  7108. end;
  7109. end;
  7110. { Detect the following:
  7111. jmp<cond> @Lbl1
  7112. jmp @Lbl2
  7113. ...
  7114. @Lbl1:
  7115. ret
  7116. Change to:
  7117. jmp<inv_cond> @Lbl2
  7118. ret
  7119. }
  7120. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  7121. begin
  7122. hp2:=getlabelwithsym(TAsmLabel(symbol));
  7123. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  7124. MatchInstruction(hp2,A_RET,[S_NO]) then
  7125. begin
  7126. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7127. { Change label address to that of the unconditional jump }
  7128. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  7129. TAsmLabel(symbol).DecRefs;
  7130. taicpu(hp1).opcode := A_RET;
  7131. taicpu(hp1).is_jmp := false;
  7132. taicpu(hp1).ops := taicpu(hp2).ops;
  7133. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  7134. case taicpu(hp2).ops of
  7135. 0:
  7136. taicpu(hp1).clearop(0);
  7137. 1:
  7138. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  7139. else
  7140. internalerror(2016041302);
  7141. end;
  7142. end;
  7143. {$ifndef i8086}
  7144. end
  7145. {
  7146. convert
  7147. j<c> .L1
  7148. mov 1,reg
  7149. jmp .L2
  7150. .L1
  7151. mov 0,reg
  7152. .L2
  7153. into
  7154. mov 0,reg
  7155. set<not(c)> reg
  7156. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7157. would destroy the flag contents
  7158. }
  7159. else if MatchInstruction(hp1,A_MOV,[]) and
  7160. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7161. {$ifdef i386}
  7162. (
  7163. { Under i386, ESI, EDI, EBP and ESP
  7164. don't have an 8-bit representation }
  7165. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7166. ) and
  7167. {$endif i386}
  7168. (taicpu(hp1).oper[0]^.val=1) and
  7169. GetNextInstruction(hp1,hp2) and
  7170. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7171. GetNextInstruction(hp2,hp3) and
  7172. { skip align }
  7173. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  7174. (hp3.typ=ait_label) and
  7175. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7176. (tai_label(hp3).labsym.getrefs=1) and
  7177. GetNextInstruction(hp3,hp4) and
  7178. MatchInstruction(hp4,A_MOV,[]) and
  7179. MatchOpType(taicpu(hp4),top_const,top_reg) and
  7180. (taicpu(hp4).oper[0]^.val=0) and
  7181. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7182. GetNextInstruction(hp4,hp5) and
  7183. (hp5.typ=ait_label) and
  7184. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  7185. (tai_label(hp5).labsym.getrefs=1) then
  7186. begin
  7187. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  7188. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  7189. { remove last label }
  7190. RemoveInstruction(hp5);
  7191. { remove second label }
  7192. RemoveInstruction(hp3);
  7193. { if align is present remove it }
  7194. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  7195. RemoveInstruction(hp3);
  7196. { remove jmp }
  7197. RemoveInstruction(hp2);
  7198. if taicpu(hp1).opsize=S_B then
  7199. RemoveInstruction(hp1)
  7200. else
  7201. taicpu(hp1).loadconst(0,0);
  7202. taicpu(hp4).opcode:=A_SETcc;
  7203. taicpu(hp4).opsize:=S_B;
  7204. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  7205. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  7206. taicpu(hp4).opercnt:=1;
  7207. taicpu(hp4).ops:=1;
  7208. taicpu(hp4).freeop(1);
  7209. RemoveCurrentP(p);
  7210. Result:=true;
  7211. exit;
  7212. end
  7213. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  7214. begin
  7215. { check for
  7216. jCC xxx
  7217. <several movs>
  7218. xxx:
  7219. }
  7220. l:=0;
  7221. while assigned(hp1) and
  7222. CanBeCMOV(hp1) and
  7223. { stop on labels }
  7224. not(hp1.typ=ait_label) do
  7225. begin
  7226. inc(l);
  7227. GetNextInstruction(hp1,hp1);
  7228. end;
  7229. if assigned(hp1) then
  7230. begin
  7231. if FindLabel(tasmlabel(symbol),hp1) then
  7232. begin
  7233. if (l<=4) and (l>0) then
  7234. begin
  7235. condition:=inverse_cond(taicpu(p).condition);
  7236. GetNextInstruction(p,hp1);
  7237. repeat
  7238. if not Assigned(hp1) then
  7239. InternalError(2018062900);
  7240. taicpu(hp1).opcode:=A_CMOVcc;
  7241. taicpu(hp1).condition:=condition;
  7242. UpdateUsedRegs(hp1);
  7243. GetNextInstruction(hp1,hp1);
  7244. until not(CanBeCMOV(hp1));
  7245. { Remember what hp1 is in case there's multiple aligns to get rid of }
  7246. hp2 := hp1;
  7247. repeat
  7248. if not Assigned(hp2) then
  7249. InternalError(2018062910);
  7250. case hp2.typ of
  7251. ait_label:
  7252. { What we expected - break out of the loop (it won't be a dead label at the top of
  7253. a cluster because that was optimised at an earlier stage) }
  7254. Break;
  7255. ait_align:
  7256. { Go to the next entry until a label is found (may be multiple aligns before it) }
  7257. begin
  7258. hp2 := tai(hp2.Next);
  7259. Continue;
  7260. end;
  7261. else
  7262. begin
  7263. { Might be a comment or temporary allocation entry }
  7264. if not (hp2.typ in SkipInstr) then
  7265. InternalError(2018062911);
  7266. hp2 := tai(hp2.Next);
  7267. Continue;
  7268. end;
  7269. end;
  7270. until False;
  7271. { Now we can safely decrement the reference count }
  7272. tasmlabel(symbol).decrefs;
  7273. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  7274. { Remove the original jump }
  7275. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  7276. GetNextInstruction(hp2, p); { Instruction after the label }
  7277. { Remove the label if this is its final reference }
  7278. if (tasmlabel(symbol).getrefs=0) then
  7279. StripLabelFast(hp1);
  7280. if Assigned(p) then
  7281. begin
  7282. UpdateUsedRegs(p);
  7283. result:=true;
  7284. end;
  7285. exit;
  7286. end;
  7287. end
  7288. else
  7289. begin
  7290. { check further for
  7291. jCC xxx
  7292. <several movs 1>
  7293. jmp yyy
  7294. xxx:
  7295. <several movs 2>
  7296. yyy:
  7297. }
  7298. { hp2 points to jmp yyy }
  7299. hp2:=hp1;
  7300. { skip hp1 to xxx (or an align right before it) }
  7301. GetNextInstruction(hp1, hp1);
  7302. if assigned(hp2) and
  7303. assigned(hp1) and
  7304. (l<=3) and
  7305. (hp2.typ=ait_instruction) and
  7306. (taicpu(hp2).is_jmp) and
  7307. (taicpu(hp2).condition=C_None) and
  7308. { real label and jump, no further references to the
  7309. label are allowed }
  7310. (tasmlabel(symbol).getrefs=1) and
  7311. FindLabel(tasmlabel(symbol),hp1) then
  7312. begin
  7313. l:=0;
  7314. { skip hp1 to <several moves 2> }
  7315. if (hp1.typ = ait_align) then
  7316. GetNextInstruction(hp1, hp1);
  7317. GetNextInstruction(hp1, hpmov2);
  7318. hp1 := hpmov2;
  7319. while assigned(hp1) and
  7320. CanBeCMOV(hp1) do
  7321. begin
  7322. inc(l);
  7323. GetNextInstruction(hp1, hp1);
  7324. end;
  7325. { hp1 points to yyy (or an align right before it) }
  7326. hp3 := hp1;
  7327. if assigned(hp1) and
  7328. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  7329. begin
  7330. condition:=inverse_cond(taicpu(p).condition);
  7331. GetNextInstruction(p,hp1);
  7332. repeat
  7333. taicpu(hp1).opcode:=A_CMOVcc;
  7334. taicpu(hp1).condition:=condition;
  7335. UpdateUsedRegs(hp1);
  7336. GetNextInstruction(hp1,hp1);
  7337. until not(assigned(hp1)) or
  7338. not(CanBeCMOV(hp1));
  7339. condition:=inverse_cond(condition);
  7340. hp1 := hpmov2;
  7341. { hp1 is now at <several movs 2> }
  7342. while Assigned(hp1) and CanBeCMOV(hp1) do
  7343. begin
  7344. taicpu(hp1).opcode:=A_CMOVcc;
  7345. taicpu(hp1).condition:=condition;
  7346. UpdateUsedRegs(hp1);
  7347. GetNextInstruction(hp1,hp1);
  7348. end;
  7349. hp1 := p;
  7350. { Get first instruction after label }
  7351. GetNextInstruction(hp3, p);
  7352. if assigned(p) and (hp3.typ = ait_align) then
  7353. GetNextInstruction(p, p);
  7354. { Don't dereference yet, as doing so will cause
  7355. GetNextInstruction to skip the label and
  7356. optional align marker. [Kit] }
  7357. GetNextInstruction(hp2, hp4);
  7358. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  7359. { remove jCC }
  7360. RemoveInstruction(hp1);
  7361. { Now we can safely decrement it }
  7362. tasmlabel(symbol).decrefs;
  7363. { Remove label xxx (it will have a ref of zero due to the initial check }
  7364. StripLabelFast(hp4);
  7365. { remove jmp }
  7366. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  7367. RemoveInstruction(hp2);
  7368. { As before, now we can safely decrement it }
  7369. tasmlabel(symbol).decrefs;
  7370. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  7371. if tasmlabel(symbol).getrefs = 0 then
  7372. StripLabelFast(hp3);
  7373. if Assigned(p) then
  7374. begin
  7375. UpdateUsedRegs(p);
  7376. result:=true;
  7377. end;
  7378. exit;
  7379. end;
  7380. end;
  7381. end;
  7382. end;
  7383. {$endif i8086}
  7384. end;
  7385. end;
  7386. end;
  7387. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  7388. var
  7389. hp1,hp2: tai;
  7390. reg_and_hp1_is_instr: Boolean;
  7391. begin
  7392. result:=false;
  7393. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  7394. GetNextInstruction(p,hp1) and
  7395. (hp1.typ = ait_instruction);
  7396. if reg_and_hp1_is_instr and
  7397. (
  7398. (taicpu(hp1).opcode <> A_LEA) or
  7399. { If the LEA instruction can be converted into an arithmetic instruction,
  7400. it may be possible to then fold it. }
  7401. (
  7402. { If the flags register is in use, don't change the instruction
  7403. to an ADD otherwise this will scramble the flags. [Kit] }
  7404. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  7405. ConvertLEA(taicpu(hp1))
  7406. )
  7407. ) and
  7408. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  7409. GetNextInstruction(hp1,hp2) and
  7410. MatchInstruction(hp2,A_MOV,[]) and
  7411. (taicpu(hp2).oper[0]^.typ = top_reg) and
  7412. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  7413. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  7414. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  7415. {$ifdef i386}
  7416. { not all registers have byte size sub registers on i386 }
  7417. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  7418. {$endif i386}
  7419. (((taicpu(hp1).ops=2) and
  7420. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7421. ((taicpu(hp1).ops=1) and
  7422. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  7423. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  7424. begin
  7425. { change movsX/movzX reg/ref, reg2
  7426. add/sub/or/... reg3/$const, reg2
  7427. mov reg2 reg/ref
  7428. to add/sub/or/... reg3/$const, reg/ref }
  7429. { by example:
  7430. movswl %si,%eax movswl %si,%eax p
  7431. decl %eax addl %edx,%eax hp1
  7432. movw %ax,%si movw %ax,%si hp2
  7433. ->
  7434. movswl %si,%eax movswl %si,%eax p
  7435. decw %eax addw %edx,%eax hp1
  7436. movw %ax,%si movw %ax,%si hp2
  7437. }
  7438. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  7439. {
  7440. ->
  7441. movswl %si,%eax movswl %si,%eax p
  7442. decw %si addw %dx,%si hp1
  7443. movw %ax,%si movw %ax,%si hp2
  7444. }
  7445. case taicpu(hp1).ops of
  7446. 1:
  7447. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  7448. 2:
  7449. begin
  7450. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  7451. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7452. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  7453. end;
  7454. else
  7455. internalerror(2008042702);
  7456. end;
  7457. {
  7458. ->
  7459. decw %si addw %dx,%si p
  7460. }
  7461. DebugMsg(SPeepholeOptimization + 'var3',p);
  7462. RemoveCurrentP(p, hp1);
  7463. RemoveInstruction(hp2);
  7464. end
  7465. else if reg_and_hp1_is_instr and
  7466. (taicpu(hp1).opcode = A_MOV) and
  7467. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7468. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  7469. {$ifdef x86_64}
  7470. { check for implicit extension to 64 bit }
  7471. or
  7472. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7473. (taicpu(hp1).opsize=S_Q) and
  7474. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  7475. )
  7476. {$endif x86_64}
  7477. )
  7478. then
  7479. begin
  7480. { change
  7481. movx %reg1,%reg2
  7482. mov %reg2,%reg3
  7483. dealloc %reg2
  7484. into
  7485. movx %reg,%reg3
  7486. }
  7487. TransferUsedRegs(TmpUsedRegs);
  7488. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7489. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7490. begin
  7491. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  7492. {$ifdef x86_64}
  7493. if (taicpu(p).opsize in [S_BL,S_WL]) and
  7494. (taicpu(hp1).opsize=S_Q) then
  7495. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  7496. else
  7497. {$endif x86_64}
  7498. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7499. RemoveInstruction(hp1);
  7500. end;
  7501. end
  7502. else if reg_and_hp1_is_instr and
  7503. (taicpu(hp1).opcode = A_MOV) and
  7504. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7505. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  7506. (taicpu(hp1).opsize=S_B)) or
  7507. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  7508. (taicpu(hp1).opsize=S_W))
  7509. {$ifdef x86_64}
  7510. or ((taicpu(p).opsize=S_LQ) and
  7511. (taicpu(hp1).opsize=S_L))
  7512. {$endif x86_64}
  7513. ) and
  7514. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  7515. begin
  7516. { change
  7517. movx %reg1,%reg2
  7518. mov %reg2,%reg3
  7519. dealloc %reg2
  7520. into
  7521. mov %reg1,%reg3
  7522. if the second mov accesses only the bits stored in reg1
  7523. }
  7524. TransferUsedRegs(TmpUsedRegs);
  7525. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7526. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7527. begin
  7528. DebugMsg(SPeepholeOptimization + 'MovxMov2Mov',p);
  7529. if taicpu(p).oper[0]^.typ=top_reg then
  7530. begin
  7531. case taicpu(hp1).opsize of
  7532. S_B:
  7533. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  7534. S_W:
  7535. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  7536. S_L:
  7537. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  7538. else
  7539. Internalerror(2020102301);
  7540. end;
  7541. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  7542. end
  7543. else
  7544. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  7545. RemoveCurrentP(p);
  7546. result:=true;
  7547. exit;
  7548. end;
  7549. end
  7550. else if reg_and_hp1_is_instr and
  7551. (taicpu(p).oper[0]^.typ = top_reg) and
  7552. (
  7553. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  7554. ) and
  7555. (taicpu(hp1).oper[0]^.typ = top_const) and
  7556. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7557. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7558. { Minimum shift value allowed is the bit difference between the sizes }
  7559. (taicpu(hp1).oper[0]^.val >=
  7560. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7561. 8 * (
  7562. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  7563. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7564. )
  7565. ) then
  7566. begin
  7567. { For:
  7568. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  7569. shl/sal ##, %reg1
  7570. Remove the movsx/movzx instruction if the shift overwrites the
  7571. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  7572. }
  7573. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  7574. RemoveCurrentP(p, hp1);
  7575. Result := True;
  7576. Exit;
  7577. end
  7578. else if reg_and_hp1_is_instr and
  7579. (taicpu(p).oper[0]^.typ = top_reg) and
  7580. (
  7581. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  7582. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  7583. ) and
  7584. (taicpu(hp1).oper[0]^.typ = top_const) and
  7585. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7586. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7587. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  7588. (taicpu(hp1).oper[0]^.val <
  7589. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7590. 8 * (
  7591. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7592. )
  7593. ) then
  7594. begin
  7595. { For:
  7596. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  7597. sar ##, %reg1 shr ##, %reg1
  7598. Move the shift to before the movx instruction if the shift value
  7599. is not too large.
  7600. }
  7601. asml.Remove(hp1);
  7602. asml.InsertBefore(hp1, p);
  7603. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  7604. case taicpu(p).opsize of
  7605. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  7606. taicpu(hp1).opsize := S_B;
  7607. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  7608. taicpu(hp1).opsize := S_W;
  7609. {$ifdef x86_64}
  7610. S_LQ:
  7611. taicpu(hp1).opsize := S_L;
  7612. {$endif}
  7613. else
  7614. InternalError(2020112401);
  7615. end;
  7616. if (taicpu(hp1).opcode = A_SHR) then
  7617. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  7618. else
  7619. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  7620. Result := True;
  7621. end
  7622. else if taicpu(p).opcode=A_MOVZX then
  7623. begin
  7624. { removes superfluous And's after movzx's }
  7625. if reg_and_hp1_is_instr and
  7626. (taicpu(hp1).opcode = A_AND) and
  7627. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7628. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  7629. {$ifdef x86_64}
  7630. { check for implicit extension to 64 bit }
  7631. or
  7632. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7633. (taicpu(hp1).opsize=S_Q) and
  7634. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  7635. )
  7636. {$endif x86_64}
  7637. )
  7638. then
  7639. begin
  7640. case taicpu(p).opsize Of
  7641. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7642. if (taicpu(hp1).oper[0]^.val = $ff) then
  7643. begin
  7644. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  7645. RemoveInstruction(hp1);
  7646. Result:=true;
  7647. exit;
  7648. end;
  7649. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7650. if (taicpu(hp1).oper[0]^.val = $ffff) then
  7651. begin
  7652. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  7653. RemoveInstruction(hp1);
  7654. Result:=true;
  7655. exit;
  7656. end;
  7657. {$ifdef x86_64}
  7658. S_LQ:
  7659. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  7660. begin
  7661. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  7662. RemoveInstruction(hp1);
  7663. Result:=true;
  7664. exit;
  7665. end;
  7666. {$endif x86_64}
  7667. else
  7668. ;
  7669. end;
  7670. { we cannot get rid of the and, but can we get rid of the movz ?}
  7671. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  7672. begin
  7673. case taicpu(p).opsize Of
  7674. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7675. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  7676. begin
  7677. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  7678. RemoveCurrentP(p,hp1);
  7679. Result:=true;
  7680. exit;
  7681. end;
  7682. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7683. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  7684. begin
  7685. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  7686. RemoveCurrentP(p,hp1);
  7687. Result:=true;
  7688. exit;
  7689. end;
  7690. {$ifdef x86_64}
  7691. S_LQ:
  7692. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  7693. begin
  7694. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  7695. RemoveCurrentP(p,hp1);
  7696. Result:=true;
  7697. exit;
  7698. end;
  7699. {$endif x86_64}
  7700. else
  7701. ;
  7702. end;
  7703. end;
  7704. end;
  7705. { changes some movzx constructs to faster synonyms (all examples
  7706. are given with eax/ax, but are also valid for other registers)}
  7707. if MatchOpType(taicpu(p),top_reg,top_reg) then
  7708. begin
  7709. case taicpu(p).opsize of
  7710. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  7711. (the machine code is equivalent to movzbl %al,%eax), but the
  7712. code generator still generates that assembler instruction and
  7713. it is silently converted. This should probably be checked.
  7714. [Kit] }
  7715. S_BW:
  7716. begin
  7717. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7718. (
  7719. not IsMOVZXAcceptable
  7720. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  7721. or (
  7722. (cs_opt_size in current_settings.optimizerswitches) and
  7723. (taicpu(p).oper[1]^.reg = NR_AX)
  7724. )
  7725. ) then
  7726. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  7727. begin
  7728. DebugMsg(SPeepholeOptimization + 'var7',p);
  7729. taicpu(p).opcode := A_AND;
  7730. taicpu(p).changeopsize(S_W);
  7731. taicpu(p).loadConst(0,$ff);
  7732. Result := True;
  7733. end
  7734. else if not IsMOVZXAcceptable and
  7735. GetNextInstruction(p, hp1) and
  7736. (tai(hp1).typ = ait_instruction) and
  7737. (taicpu(hp1).opcode = A_AND) and
  7738. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7739. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7740. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  7741. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  7742. begin
  7743. DebugMsg(SPeepholeOptimization + 'var8',p);
  7744. taicpu(p).opcode := A_MOV;
  7745. taicpu(p).changeopsize(S_W);
  7746. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  7747. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7748. Result := True;
  7749. end;
  7750. end;
  7751. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  7752. S_BL:
  7753. begin
  7754. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7755. (
  7756. not IsMOVZXAcceptable
  7757. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  7758. or (
  7759. (cs_opt_size in current_settings.optimizerswitches) and
  7760. (taicpu(p).oper[1]^.reg = NR_EAX)
  7761. )
  7762. ) then
  7763. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  7764. begin
  7765. DebugMsg(SPeepholeOptimization + 'var9',p);
  7766. taicpu(p).opcode := A_AND;
  7767. taicpu(p).changeopsize(S_L);
  7768. taicpu(p).loadConst(0,$ff);
  7769. Result := True;
  7770. end
  7771. else if not IsMOVZXAcceptable and
  7772. GetNextInstruction(p, hp1) and
  7773. (tai(hp1).typ = ait_instruction) and
  7774. (taicpu(hp1).opcode = A_AND) and
  7775. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7776. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7777. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  7778. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  7779. begin
  7780. DebugMsg(SPeepholeOptimization + 'var10',p);
  7781. taicpu(p).opcode := A_MOV;
  7782. taicpu(p).changeopsize(S_L);
  7783. { do not use R_SUBWHOLE
  7784. as movl %rdx,%eax
  7785. is invalid in assembler PM }
  7786. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  7787. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7788. Result := True;
  7789. end;
  7790. end;
  7791. {$endif i8086}
  7792. S_WL:
  7793. if not IsMOVZXAcceptable then
  7794. begin
  7795. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  7796. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  7797. begin
  7798. DebugMsg(SPeepholeOptimization + 'var11',p);
  7799. taicpu(p).opcode := A_AND;
  7800. taicpu(p).changeopsize(S_L);
  7801. taicpu(p).loadConst(0,$ffff);
  7802. Result := True;
  7803. end
  7804. else if GetNextInstruction(p, hp1) and
  7805. (tai(hp1).typ = ait_instruction) and
  7806. (taicpu(hp1).opcode = A_AND) and
  7807. (taicpu(hp1).oper[0]^.typ = top_const) and
  7808. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7809. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7810. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  7811. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  7812. begin
  7813. DebugMsg(SPeepholeOptimization + 'var12',p);
  7814. taicpu(p).opcode := A_MOV;
  7815. taicpu(p).changeopsize(S_L);
  7816. { do not use R_SUBWHOLE
  7817. as movl %rdx,%eax
  7818. is invalid in assembler PM }
  7819. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  7820. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  7821. Result := True;
  7822. end;
  7823. end;
  7824. else
  7825. InternalError(2017050705);
  7826. end;
  7827. end
  7828. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  7829. begin
  7830. if GetNextInstruction(p, hp1) and
  7831. (tai(hp1).typ = ait_instruction) and
  7832. (taicpu(hp1).opcode = A_AND) and
  7833. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7834. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7835. begin
  7836. //taicpu(p).opcode := A_MOV;
  7837. case taicpu(p).opsize Of
  7838. S_BL:
  7839. begin
  7840. DebugMsg(SPeepholeOptimization + 'var13',p);
  7841. taicpu(hp1).changeopsize(S_L);
  7842. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7843. end;
  7844. S_WL:
  7845. begin
  7846. DebugMsg(SPeepholeOptimization + 'var14',p);
  7847. taicpu(hp1).changeopsize(S_L);
  7848. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  7849. end;
  7850. S_BW:
  7851. begin
  7852. DebugMsg(SPeepholeOptimization + 'var15',p);
  7853. taicpu(hp1).changeopsize(S_W);
  7854. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7855. end;
  7856. else
  7857. Internalerror(2017050704)
  7858. end;
  7859. Result := True;
  7860. end;
  7861. end;
  7862. end;
  7863. end;
  7864. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  7865. var
  7866. hp1, hp2 : tai;
  7867. MaskLength : Cardinal;
  7868. MaskedBits : TCgInt;
  7869. begin
  7870. Result:=false;
  7871. { There are no optimisations for reference targets }
  7872. if (taicpu(p).oper[1]^.typ <> top_reg) then
  7873. Exit;
  7874. while GetNextInstruction(p, hp1) and
  7875. (hp1.typ = ait_instruction) do
  7876. begin
  7877. if (taicpu(p).oper[0]^.typ = top_const) then
  7878. begin
  7879. case taicpu(hp1).opcode of
  7880. A_AND:
  7881. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  7882. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7883. { the second register must contain the first one, so compare their subreg types }
  7884. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  7885. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  7886. { change
  7887. and const1, reg
  7888. and const2, reg
  7889. to
  7890. and (const1 and const2), reg
  7891. }
  7892. begin
  7893. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  7894. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  7895. RemoveCurrentP(p, hp1);
  7896. Result:=true;
  7897. exit;
  7898. end;
  7899. A_CMP:
  7900. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  7901. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  7902. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7903. { Just check that the condition on the next instruction is compatible }
  7904. GetNextInstruction(hp1, hp2) and
  7905. (hp2.typ = ait_instruction) and
  7906. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  7907. then
  7908. { change
  7909. and 2^n, reg
  7910. cmp 2^n, reg
  7911. j(c) / set(c) / cmov(c) (c is equal or not equal)
  7912. to
  7913. and 2^n, reg
  7914. test reg, reg
  7915. j(~c) / set(~c) / cmov(~c)
  7916. }
  7917. begin
  7918. { Keep TEST instruction in, rather than remove it, because
  7919. it may trigger other optimisations such as MovAndTest2Test }
  7920. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  7921. taicpu(hp1).opcode := A_TEST;
  7922. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  7923. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  7924. Result := True;
  7925. Exit;
  7926. end;
  7927. A_MOVZX:
  7928. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7929. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  7930. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7931. (
  7932. (
  7933. (taicpu(p).opsize=S_W) and
  7934. (taicpu(hp1).opsize=S_BW)
  7935. ) or
  7936. (
  7937. (taicpu(p).opsize=S_L) and
  7938. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  7939. )
  7940. {$ifdef x86_64}
  7941. or
  7942. (
  7943. (taicpu(p).opsize=S_Q) and
  7944. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  7945. )
  7946. {$endif x86_64}
  7947. ) then
  7948. begin
  7949. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  7950. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  7951. ) or
  7952. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  7953. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  7954. then
  7955. begin
  7956. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  7957. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  7958. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  7959. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  7960. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  7961. }
  7962. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  7963. RemoveInstruction(hp1);
  7964. { See if there are other optimisations possible }
  7965. Continue;
  7966. end;
  7967. end;
  7968. A_SHL:
  7969. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  7970. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7971. begin
  7972. {$ifopt R+}
  7973. {$define RANGE_WAS_ON}
  7974. {$R-}
  7975. {$endif}
  7976. { get length of potential and mask }
  7977. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  7978. { really a mask? }
  7979. {$ifdef RANGE_WAS_ON}
  7980. {$R+}
  7981. {$endif}
  7982. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  7983. { unmasked part shifted out? }
  7984. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  7985. begin
  7986. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  7987. RemoveCurrentP(p, hp1);
  7988. Result:=true;
  7989. exit;
  7990. end;
  7991. end;
  7992. A_SHR:
  7993. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  7994. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  7995. (taicpu(hp1).oper[0]^.val <= 63) then
  7996. begin
  7997. { Does SHR combined with the AND cover all the bits?
  7998. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  7999. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  8000. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  8001. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  8002. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  8003. begin
  8004. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  8005. RemoveCurrentP(p, hp1);
  8006. Result := True;
  8007. Exit;
  8008. end;
  8009. end;
  8010. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8011. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  8012. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  8013. begin
  8014. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8015. (
  8016. (
  8017. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8018. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  8019. ) or (
  8020. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8021. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  8022. {$ifdef x86_64}
  8023. ) or (
  8024. (taicpu(hp1).opsize = S_LQ) and
  8025. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  8026. {$endif x86_64}
  8027. )
  8028. ) then
  8029. begin
  8030. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  8031. begin
  8032. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  8033. RemoveInstruction(hp1);
  8034. { See if there are other optimisations possible }
  8035. Continue;
  8036. end;
  8037. { The super-registers are the same though.
  8038. Note that this change by itself doesn't improve
  8039. code speed, but it opens up other optimisations. }
  8040. {$ifdef x86_64}
  8041. { Convert 64-bit register to 32-bit }
  8042. case taicpu(hp1).opsize of
  8043. S_BQ:
  8044. begin
  8045. taicpu(hp1).opsize := S_BL;
  8046. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8047. end;
  8048. S_WQ:
  8049. begin
  8050. taicpu(hp1).opsize := S_WL;
  8051. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8052. end
  8053. else
  8054. ;
  8055. end;
  8056. {$endif x86_64}
  8057. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  8058. taicpu(hp1).opcode := A_MOVZX;
  8059. { See if there are other optimisations possible }
  8060. Continue;
  8061. end;
  8062. end;
  8063. else
  8064. ;
  8065. end;
  8066. end;
  8067. if (taicpu(hp1).is_jmp) and
  8068. (taicpu(hp1).opcode<>A_JMP) and
  8069. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  8070. begin
  8071. { change
  8072. and x, reg
  8073. jxx
  8074. to
  8075. test x, reg
  8076. jxx
  8077. if reg is deallocated before the
  8078. jump, but only if it's a conditional jump (PFV)
  8079. }
  8080. taicpu(p).opcode := A_TEST;
  8081. Exit;
  8082. end;
  8083. Break;
  8084. end;
  8085. { Lone AND tests }
  8086. if (taicpu(p).oper[0]^.typ = top_const) then
  8087. begin
  8088. {
  8089. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  8090. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  8091. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  8092. }
  8093. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  8094. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  8095. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  8096. begin
  8097. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  8098. if taicpu(p).opsize = S_L then
  8099. begin
  8100. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  8101. Result := True;
  8102. end;
  8103. end;
  8104. end;
  8105. { Backward check to determine necessity of and %reg,%reg }
  8106. if (taicpu(p).oper[0]^.typ = top_reg) and
  8107. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  8108. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  8109. GetLastInstruction(p, hp2) and
  8110. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  8111. { Check size of adjacent instruction to determine if the AND is
  8112. effectively a null operation }
  8113. (
  8114. (taicpu(p).opsize = taicpu(hp2).opsize) or
  8115. { Note: Don't include S_Q }
  8116. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  8117. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  8118. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  8119. ) then
  8120. begin
  8121. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  8122. { If GetNextInstruction returned False, hp1 will be nil }
  8123. RemoveCurrentP(p, hp1);
  8124. Result := True;
  8125. Exit;
  8126. end;
  8127. end;
  8128. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  8129. var
  8130. hp1: tai; NewRef: TReference;
  8131. { This entire nested function is used in an if-statement below, but we
  8132. want to avoid all the used reg transfers and GetNextInstruction calls
  8133. until we really have to check }
  8134. function MemRegisterNotUsedLater: Boolean; inline;
  8135. var
  8136. hp2: tai;
  8137. begin
  8138. TransferUsedRegs(TmpUsedRegs);
  8139. hp2 := p;
  8140. repeat
  8141. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8142. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8143. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  8144. end;
  8145. begin
  8146. Result := False;
  8147. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  8148. Exit;
  8149. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  8150. begin
  8151. { Change:
  8152. add %reg2,%reg1
  8153. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  8154. To:
  8155. mov/s/z #(%reg1,%reg2),%reg1
  8156. }
  8157. if MatchOpType(taicpu(p), top_reg, top_reg) and
  8158. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  8159. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  8160. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  8161. (
  8162. (
  8163. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  8164. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  8165. { r/esp cannot be an index }
  8166. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  8167. ) or (
  8168. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  8169. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  8170. )
  8171. ) and (
  8172. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  8173. (
  8174. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  8175. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8176. MemRegisterNotUsedLater
  8177. )
  8178. ) then
  8179. begin
  8180. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  8181. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  8182. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  8183. RemoveCurrentp(p, hp1);
  8184. Result := True;
  8185. Exit;
  8186. end;
  8187. { Change:
  8188. addl/q $x,%reg1
  8189. movl/q %reg1,%reg2
  8190. To:
  8191. leal/q $x(%reg1),%reg2
  8192. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8193. Breaks the dependency chain.
  8194. }
  8195. if MatchOpType(taicpu(p),top_const,top_reg) and
  8196. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8197. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8198. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8199. (
  8200. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  8201. not (cs_opt_size in current_settings.optimizerswitches) or
  8202. (
  8203. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8204. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8205. )
  8206. ) then
  8207. begin
  8208. { Change the MOV instruction to a LEA instruction, and update the
  8209. first operand }
  8210. reference_reset(NewRef, 1, []);
  8211. NewRef.base := taicpu(p).oper[1]^.reg;
  8212. NewRef.scalefactor := 1;
  8213. NewRef.offset := taicpu(p).oper[0]^.val;
  8214. taicpu(hp1).opcode := A_LEA;
  8215. taicpu(hp1).loadref(0, NewRef);
  8216. TransferUsedRegs(TmpUsedRegs);
  8217. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8218. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8219. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8220. begin
  8221. { Move what is now the LEA instruction to before the SUB instruction }
  8222. Asml.Remove(hp1);
  8223. Asml.InsertBefore(hp1, p);
  8224. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8225. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  8226. p := hp1;
  8227. end
  8228. else
  8229. begin
  8230. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8231. RemoveCurrentP(p, hp1);
  8232. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  8233. end;
  8234. Result := True;
  8235. end;
  8236. end;
  8237. end;
  8238. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  8239. begin
  8240. Result:=false;
  8241. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8242. begin
  8243. if MatchReference(taicpu(p).oper[0]^.ref^,taicpu(p).oper[1]^.reg,NR_INVALID) and
  8244. (taicpu(p).oper[0]^.ref^.index<>NR_NO) then
  8245. begin
  8246. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.base);
  8247. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.index);
  8248. taicpu(p).opcode:=A_ADD;
  8249. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  8250. result:=true;
  8251. end
  8252. else if MatchReference(taicpu(p).oper[0]^.ref^,NR_INVALID,taicpu(p).oper[1]^.reg) and
  8253. (taicpu(p).oper[0]^.ref^.base<>NR_NO) then
  8254. begin
  8255. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.index);
  8256. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.base);
  8257. taicpu(p).opcode:=A_ADD;
  8258. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  8259. result:=true;
  8260. end;
  8261. end;
  8262. end;
  8263. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  8264. var
  8265. hp1: tai; NewRef: TReference;
  8266. begin
  8267. { Change:
  8268. subl/q $x,%reg1
  8269. movl/q %reg1,%reg2
  8270. To:
  8271. leal/q $-x(%reg1),%reg2
  8272. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8273. Breaks the dependency chain and potentially permits the removal of
  8274. a CMP instruction if one follows.
  8275. }
  8276. Result := False;
  8277. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8278. MatchOpType(taicpu(p),top_const,top_reg) and
  8279. GetNextInstruction(p, hp1) and
  8280. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8281. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8282. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8283. (
  8284. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  8285. not (cs_opt_size in current_settings.optimizerswitches) or
  8286. (
  8287. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8288. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8289. )
  8290. ) then
  8291. begin
  8292. { Change the MOV instruction to a LEA instruction, and update the
  8293. first operand }
  8294. reference_reset(NewRef, 1, []);
  8295. NewRef.base := taicpu(p).oper[1]^.reg;
  8296. NewRef.scalefactor := 1;
  8297. NewRef.offset := -taicpu(p).oper[0]^.val;
  8298. taicpu(hp1).opcode := A_LEA;
  8299. taicpu(hp1).loadref(0, NewRef);
  8300. TransferUsedRegs(TmpUsedRegs);
  8301. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8302. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8303. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8304. begin
  8305. { Move what is now the LEA instruction to before the SUB instruction }
  8306. Asml.Remove(hp1);
  8307. Asml.InsertBefore(hp1, p);
  8308. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8309. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  8310. p := hp1;
  8311. end
  8312. else
  8313. begin
  8314. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8315. RemoveCurrentP(p, hp1);
  8316. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  8317. end;
  8318. Result := True;
  8319. end;
  8320. end;
  8321. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  8322. begin
  8323. { we can skip all instructions not messing with the stack pointer }
  8324. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  8325. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  8326. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  8327. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  8328. ({(taicpu(hp1).ops=0) or }
  8329. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  8330. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  8331. ) and }
  8332. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  8333. )
  8334. ) do
  8335. GetNextInstruction(hp1,hp1);
  8336. Result:=assigned(hp1);
  8337. end;
  8338. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  8339. var
  8340. hp1, hp2, hp3, hp4, hp5: tai;
  8341. begin
  8342. Result:=false;
  8343. hp5:=nil;
  8344. { replace
  8345. leal(q) x(<stackpointer>),<stackpointer>
  8346. call procname
  8347. leal(q) -x(<stackpointer>),<stackpointer>
  8348. ret
  8349. by
  8350. jmp procname
  8351. but do it only on level 4 because it destroys stack back traces
  8352. }
  8353. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8354. MatchOpType(taicpu(p),top_ref,top_reg) and
  8355. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8356. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  8357. { the -8 or -24 are not required, but bail out early if possible,
  8358. higher values are unlikely }
  8359. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  8360. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  8361. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  8362. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  8363. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  8364. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8365. GetNextInstruction(p, hp1) and
  8366. { Take a copy of hp1 }
  8367. SetAndTest(hp1, hp4) and
  8368. { trick to skip label }
  8369. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8370. SkipSimpleInstructions(hp1) and
  8371. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8372. GetNextInstruction(hp1, hp2) and
  8373. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  8374. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  8375. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  8376. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8377. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  8378. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  8379. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  8380. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  8381. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8382. GetNextInstruction(hp2, hp3) and
  8383. { trick to skip label }
  8384. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8385. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8386. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8387. SetAndTest(hp3,hp5) and
  8388. GetNextInstruction(hp3,hp3) and
  8389. MatchInstruction(hp3,A_RET,[S_NO])
  8390. )
  8391. ) and
  8392. (taicpu(hp3).ops=0) then
  8393. begin
  8394. taicpu(hp1).opcode := A_JMP;
  8395. taicpu(hp1).is_jmp := true;
  8396. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  8397. RemoveCurrentP(p, hp4);
  8398. RemoveInstruction(hp2);
  8399. RemoveInstruction(hp3);
  8400. if Assigned(hp5) then
  8401. begin
  8402. AsmL.Remove(hp5);
  8403. ASmL.InsertBefore(hp5,hp1)
  8404. end;
  8405. Result:=true;
  8406. end;
  8407. end;
  8408. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  8409. {$ifdef x86_64}
  8410. var
  8411. hp1, hp2, hp3, hp4, hp5: tai;
  8412. {$endif x86_64}
  8413. begin
  8414. Result:=false;
  8415. {$ifdef x86_64}
  8416. hp5:=nil;
  8417. { replace
  8418. push %rax
  8419. call procname
  8420. pop %rcx
  8421. ret
  8422. by
  8423. jmp procname
  8424. but do it only on level 4 because it destroys stack back traces
  8425. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  8426. for all supported calling conventions
  8427. }
  8428. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8429. MatchOpType(taicpu(p),top_reg) and
  8430. (taicpu(p).oper[0]^.reg=NR_RAX) and
  8431. GetNextInstruction(p, hp1) and
  8432. { Take a copy of hp1 }
  8433. SetAndTest(hp1, hp4) and
  8434. { trick to skip label }
  8435. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8436. SkipSimpleInstructions(hp1) and
  8437. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8438. GetNextInstruction(hp1, hp2) and
  8439. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  8440. MatchOpType(taicpu(hp2),top_reg) and
  8441. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  8442. GetNextInstruction(hp2, hp3) and
  8443. { trick to skip label }
  8444. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8445. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8446. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8447. SetAndTest(hp3,hp5) and
  8448. GetNextInstruction(hp3,hp3) and
  8449. MatchInstruction(hp3,A_RET,[S_NO])
  8450. )
  8451. ) and
  8452. (taicpu(hp3).ops=0) then
  8453. begin
  8454. taicpu(hp1).opcode := A_JMP;
  8455. taicpu(hp1).is_jmp := true;
  8456. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  8457. RemoveCurrentP(p, hp4);
  8458. RemoveInstruction(hp2);
  8459. RemoveInstruction(hp3);
  8460. if Assigned(hp5) then
  8461. begin
  8462. AsmL.Remove(hp5);
  8463. ASmL.InsertBefore(hp5,hp1)
  8464. end;
  8465. Result:=true;
  8466. end;
  8467. {$endif x86_64}
  8468. end;
  8469. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  8470. var
  8471. Value, RegName: string;
  8472. begin
  8473. Result:=false;
  8474. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  8475. begin
  8476. case taicpu(p).oper[0]^.val of
  8477. 0:
  8478. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  8479. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8480. begin
  8481. { change "mov $0,%reg" into "xor %reg,%reg" }
  8482. taicpu(p).opcode := A_XOR;
  8483. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  8484. Result := True;
  8485. end;
  8486. $1..$FFFFFFFF:
  8487. begin
  8488. { Code size reduction by J. Gareth "Kit" Moreton }
  8489. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  8490. case taicpu(p).opsize of
  8491. S_Q:
  8492. begin
  8493. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  8494. Value := debug_tostr(taicpu(p).oper[0]^.val);
  8495. { The actual optimization }
  8496. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8497. taicpu(p).changeopsize(S_L);
  8498. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  8499. Result := True;
  8500. end;
  8501. else
  8502. { Do nothing };
  8503. end;
  8504. end;
  8505. -1:
  8506. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  8507. if (cs_opt_size in current_settings.optimizerswitches) and
  8508. (taicpu(p).opsize <> S_B) and
  8509. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8510. begin
  8511. { change "mov $-1,%reg" into "or $-1,%reg" }
  8512. { NOTES:
  8513. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  8514. - This operation creates a false dependency on the register, so only do it when optimising for size
  8515. - 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
  8516. }
  8517. taicpu(p).opcode := A_OR;
  8518. Result := True;
  8519. end;
  8520. end;
  8521. end;
  8522. end;
  8523. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  8524. var
  8525. hp1: tai;
  8526. begin
  8527. { Detect:
  8528. andw x, %ax (0 <= x < $8000)
  8529. ...
  8530. movzwl %ax,%eax
  8531. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8532. }
  8533. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  8534. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8535. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  8536. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8537. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8538. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8539. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8540. begin
  8541. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  8542. taicpu(hp1).opcode := A_CWDE;
  8543. taicpu(hp1).clearop(0);
  8544. taicpu(hp1).clearop(1);
  8545. taicpu(hp1).ops := 0;
  8546. { A change was made, but not with p, so move forward 1 }
  8547. p := tai(p.Next);
  8548. Result := True;
  8549. end;
  8550. end;
  8551. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  8552. begin
  8553. Result := False;
  8554. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  8555. Exit;
  8556. { Convert:
  8557. movswl %ax,%eax -> cwtl
  8558. movslq %eax,%rax -> cdqe
  8559. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  8560. refer to the same opcode and depends only on the assembler's
  8561. current operand-size attribute. [Kit]
  8562. }
  8563. with taicpu(p) do
  8564. case opsize of
  8565. S_WL:
  8566. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  8567. begin
  8568. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  8569. opcode := A_CWDE;
  8570. clearop(0);
  8571. clearop(1);
  8572. ops := 0;
  8573. Result := True;
  8574. end;
  8575. {$ifdef x86_64}
  8576. S_LQ:
  8577. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  8578. begin
  8579. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  8580. opcode := A_CDQE;
  8581. clearop(0);
  8582. clearop(1);
  8583. ops := 0;
  8584. Result := True;
  8585. end;
  8586. {$endif x86_64}
  8587. else
  8588. ;
  8589. end;
  8590. end;
  8591. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  8592. var
  8593. hp1: tai;
  8594. begin
  8595. { Detect:
  8596. shr x, %ax (x > 0)
  8597. ...
  8598. movzwl %ax,%eax
  8599. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8600. }
  8601. Result := False;
  8602. if MatchOpType(taicpu(p), top_const, top_reg) and
  8603. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8604. (taicpu(p).oper[0]^.val > 0) and
  8605. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8606. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8607. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8608. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8609. begin
  8610. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  8611. taicpu(hp1).opcode := A_CWDE;
  8612. taicpu(hp1).clearop(0);
  8613. taicpu(hp1).clearop(1);
  8614. taicpu(hp1).ops := 0;
  8615. { A change was made, but not with p, so move forward 1 }
  8616. p := tai(p.Next);
  8617. Result := True;
  8618. end;
  8619. end;
  8620. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  8621. begin
  8622. Result:=false;
  8623. { change "cmp $0, %reg" to "test %reg, %reg" }
  8624. if MatchOpType(taicpu(p),top_const,top_reg) and
  8625. (taicpu(p).oper[0]^.val = 0) then
  8626. begin
  8627. taicpu(p).opcode := A_TEST;
  8628. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8629. Result:=true;
  8630. end;
  8631. end;
  8632. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  8633. var
  8634. IsTestConstX : Boolean;
  8635. hp1,hp2 : tai;
  8636. begin
  8637. Result:=false;
  8638. { removes the line marked with (x) from the sequence
  8639. and/or/xor/add/sub/... $x, %y
  8640. test/or %y, %y | test $-1, %y (x)
  8641. j(n)z _Label
  8642. as the first instruction already adjusts the ZF
  8643. %y operand may also be a reference }
  8644. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  8645. MatchOperand(taicpu(p).oper[0]^,-1);
  8646. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  8647. GetLastInstruction(p, hp1) and
  8648. (tai(hp1).typ = ait_instruction) and
  8649. GetNextInstruction(p,hp2) and
  8650. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  8651. case taicpu(hp1).opcode Of
  8652. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  8653. begin
  8654. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  8655. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8656. { and in case of carry for A(E)/B(E)/C/NC }
  8657. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  8658. ((taicpu(hp1).opcode <> A_ADD) and
  8659. (taicpu(hp1).opcode <> A_SUB))) then
  8660. begin
  8661. RemoveCurrentP(p, hp2);
  8662. Result:=true;
  8663. Exit;
  8664. end;
  8665. end;
  8666. A_SHL, A_SAL, A_SHR, A_SAR:
  8667. begin
  8668. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  8669. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  8670. { therefore, it's only safe to do this optimization for }
  8671. { shifts by a (nonzero) constant }
  8672. (taicpu(hp1).oper[0]^.typ = top_const) and
  8673. (taicpu(hp1).oper[0]^.val <> 0) and
  8674. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8675. { and in case of carry for A(E)/B(E)/C/NC }
  8676. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  8677. begin
  8678. RemoveCurrentP(p, hp2);
  8679. Result:=true;
  8680. Exit;
  8681. end;
  8682. end;
  8683. A_DEC, A_INC, A_NEG:
  8684. begin
  8685. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  8686. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8687. { and in case of carry for A(E)/B(E)/C/NC }
  8688. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  8689. begin
  8690. case taicpu(hp1).opcode of
  8691. A_DEC, A_INC:
  8692. { replace inc/dec with add/sub 1, because inc/dec doesn't set the carry flag }
  8693. begin
  8694. case taicpu(hp1).opcode Of
  8695. A_DEC: taicpu(hp1).opcode := A_SUB;
  8696. A_INC: taicpu(hp1).opcode := A_ADD;
  8697. else
  8698. ;
  8699. end;
  8700. taicpu(hp1).loadoper(1,taicpu(hp1).oper[0]^);
  8701. taicpu(hp1).loadConst(0,1);
  8702. taicpu(hp1).ops:=2;
  8703. end;
  8704. else
  8705. ;
  8706. end;
  8707. RemoveCurrentP(p, hp2);
  8708. Result:=true;
  8709. Exit;
  8710. end;
  8711. end
  8712. else
  8713. ;
  8714. end; { case }
  8715. { change "test $-1,%reg" into "test %reg,%reg" }
  8716. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  8717. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  8718. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  8719. if MatchInstruction(p, A_OR, []) and
  8720. { Can only match if they're both registers }
  8721. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  8722. begin
  8723. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  8724. taicpu(p).opcode := A_TEST;
  8725. { No need to set Result to True, as we've done all the optimisations we can }
  8726. end;
  8727. end;
  8728. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  8729. var
  8730. hp1,hp3 : tai;
  8731. {$ifndef x86_64}
  8732. hp2 : taicpu;
  8733. {$endif x86_64}
  8734. begin
  8735. Result:=false;
  8736. hp3:=nil;
  8737. {$ifndef x86_64}
  8738. { don't do this on modern CPUs, this really hurts them due to
  8739. broken call/ret pairing }
  8740. if (current_settings.optimizecputype < cpu_Pentium2) and
  8741. not(cs_create_pic in current_settings.moduleswitches) and
  8742. GetNextInstruction(p, hp1) and
  8743. MatchInstruction(hp1,A_JMP,[S_NO]) and
  8744. MatchOpType(taicpu(hp1),top_ref) and
  8745. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  8746. begin
  8747. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  8748. InsertLLItem(p.previous, p, hp2);
  8749. taicpu(p).opcode := A_JMP;
  8750. taicpu(p).is_jmp := true;
  8751. RemoveInstruction(hp1);
  8752. Result:=true;
  8753. end
  8754. else
  8755. {$endif x86_64}
  8756. { replace
  8757. call procname
  8758. ret
  8759. by
  8760. jmp procname
  8761. but do it only on level 4 because it destroys stack back traces
  8762. else if the subroutine is marked as no return, remove the ret
  8763. }
  8764. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  8765. (po_noreturn in current_procinfo.procdef.procoptions)) and
  8766. GetNextInstruction(p, hp1) and
  8767. (MatchInstruction(hp1,A_RET,[S_NO]) or
  8768. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  8769. SetAndTest(hp1,hp3) and
  8770. GetNextInstruction(hp1,hp1) and
  8771. MatchInstruction(hp1,A_RET,[S_NO])
  8772. )
  8773. ) and
  8774. (taicpu(hp1).ops=0) then
  8775. begin
  8776. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8777. { we might destroy stack alignment here if we do not do a call }
  8778. (target_info.stackalign<=sizeof(SizeUInt)) then
  8779. begin
  8780. taicpu(p).opcode := A_JMP;
  8781. taicpu(p).is_jmp := true;
  8782. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  8783. end
  8784. else
  8785. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  8786. RemoveInstruction(hp1);
  8787. if Assigned(hp3) then
  8788. begin
  8789. AsmL.Remove(hp3);
  8790. AsmL.InsertBefore(hp3,p)
  8791. end;
  8792. Result:=true;
  8793. end;
  8794. end;
  8795. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  8796. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  8797. begin
  8798. case OpSize of
  8799. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8800. Result := (Val <= $FF) and (Val >= -128);
  8801. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8802. Result := (Val <= $FFFF) and (Val >= -32768);
  8803. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  8804. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  8805. else
  8806. Result := True;
  8807. end;
  8808. end;
  8809. var
  8810. hp1, hp2 : tai;
  8811. SizeChange: Boolean;
  8812. PreMessage: string;
  8813. begin
  8814. Result := False;
  8815. if (taicpu(p).oper[0]^.typ = top_reg) and
  8816. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8817. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  8818. begin
  8819. { Change (using movzbl %al,%eax as an example):
  8820. movzbl %al, %eax movzbl %al, %eax
  8821. cmpl x, %eax testl %eax,%eax
  8822. To:
  8823. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  8824. movzbl %al, %eax movzbl %al, %eax
  8825. Smaller instruction and minimises pipeline stall as the CPU
  8826. doesn't have to wait for the register to get zero-extended. [Kit]
  8827. Also allow if the smaller of the two registers is being checked,
  8828. as this still removes the false dependency.
  8829. }
  8830. if
  8831. (
  8832. (
  8833. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  8834. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  8835. ) or (
  8836. { If MatchOperand returns True, they must both be registers }
  8837. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  8838. )
  8839. ) and
  8840. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  8841. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  8842. begin
  8843. 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);
  8844. asml.Remove(hp1);
  8845. asml.InsertBefore(hp1, p);
  8846. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  8847. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  8848. begin
  8849. taicpu(hp1).opcode := A_TEST;
  8850. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  8851. end;
  8852. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  8853. case taicpu(p).opsize of
  8854. S_BW, S_BL:
  8855. begin
  8856. SizeChange := taicpu(hp1).opsize <> S_B;
  8857. taicpu(hp1).changeopsize(S_B);
  8858. end;
  8859. S_WL:
  8860. begin
  8861. SizeChange := taicpu(hp1).opsize <> S_W;
  8862. taicpu(hp1).changeopsize(S_W);
  8863. end
  8864. else
  8865. InternalError(2020112701);
  8866. end;
  8867. UpdateUsedRegs(tai(p.Next));
  8868. { Check if the register is used aferwards - if not, we can
  8869. remove the movzx instruction completely }
  8870. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  8871. begin
  8872. { Hp1 is a better position than p for debugging purposes }
  8873. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  8874. RemoveCurrentp(p, hp1);
  8875. Result := True;
  8876. end;
  8877. if SizeChange then
  8878. DebugMsg(SPeepholeOptimization + PreMessage +
  8879. 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)
  8880. else
  8881. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  8882. Exit;
  8883. end;
  8884. { Change (using movzwl %ax,%eax as an example):
  8885. movzwl %ax, %eax
  8886. movb %al, (dest) (Register is smaller than read register in movz)
  8887. To:
  8888. movb %al, (dest) (Move one back to avoid a false dependency)
  8889. movzwl %ax, %eax
  8890. }
  8891. if (taicpu(hp1).opcode = A_MOV) and
  8892. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8893. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  8894. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  8895. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  8896. begin
  8897. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  8898. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  8899. asml.Remove(hp1);
  8900. asml.InsertBefore(hp1, p);
  8901. if taicpu(hp1).oper[1]^.typ = top_reg then
  8902. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  8903. { Check if the register is used aferwards - if not, we can
  8904. remove the movzx instruction completely }
  8905. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  8906. begin
  8907. { Hp1 is a better position than p for debugging purposes }
  8908. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  8909. RemoveCurrentp(p, hp1);
  8910. Result := True;
  8911. end;
  8912. Exit;
  8913. end;
  8914. end;
  8915. {$ifdef x86_64}
  8916. { Code size reduction by J. Gareth "Kit" Moreton }
  8917. { Convert MOVZBQ and MOVZWQ to MOVZBL and MOVZWL respectively if it removes the REX prefix }
  8918. if (taicpu(p).opsize in [S_BQ, S_WQ]) and
  8919. (getsupreg(taicpu(p).oper[1]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP])
  8920. then
  8921. begin
  8922. { Has 64-bit register name and opcode suffix }
  8923. PreMessage := 'movz' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' -> movz';
  8924. { The actual optimization }
  8925. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8926. if taicpu(p).opsize = S_BQ then
  8927. taicpu(p).changeopsize(S_BL)
  8928. else
  8929. taicpu(p).changeopsize(S_WL);
  8930. DebugMsg(SPeepholeOptimization + PreMessage +
  8931. debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (removes REX prefix)', p);
  8932. end;
  8933. {$endif}
  8934. end;
  8935. {$ifdef x86_64}
  8936. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  8937. var
  8938. PreMessage, RegName: string;
  8939. begin
  8940. { Code size reduction by J. Gareth "Kit" Moreton }
  8941. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  8942. as this removes the REX prefix }
  8943. Result := False;
  8944. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  8945. Exit;
  8946. if taicpu(p).oper[0]^.typ <> top_reg then
  8947. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  8948. InternalError(2018011500);
  8949. case taicpu(p).opsize of
  8950. S_Q:
  8951. begin
  8952. if (getsupreg(taicpu(p).oper[0]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP]) then
  8953. begin
  8954. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  8955. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  8956. { The actual optimization }
  8957. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8958. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8959. taicpu(p).changeopsize(S_L);
  8960. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  8961. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (removes REX prefix)', p);
  8962. end;
  8963. end;
  8964. else
  8965. ;
  8966. end;
  8967. end;
  8968. {$endif}
  8969. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  8970. var
  8971. OperIdx: Integer;
  8972. begin
  8973. for OperIdx := 0 to p.ops - 1 do
  8974. if p.oper[OperIdx]^.typ = top_ref then
  8975. optimize_ref(p.oper[OperIdx]^.ref^, False);
  8976. end;
  8977. end.