aoptx86.pas 416 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798
  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]^) and
  2269. GetNextInstruction(hp2,hp3) and
  2270. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2271. (taicpu(hp3).condition in [C_E,C_NE]) then
  2272. begin
  2273. TransferUsedRegs(TmpUsedRegs);
  2274. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2275. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2276. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2277. begin
  2278. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2279. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2280. taicpu(hp1).opcode:=A_TEST;
  2281. RemoveInstruction(hp2);
  2282. RemoveCurrentP(p, hp1);
  2283. Result:=true;
  2284. exit;
  2285. end;
  2286. end;
  2287. end
  2288. else if IsMOVZXAcceptable and
  2289. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2290. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2291. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2292. then
  2293. begin
  2294. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2295. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2296. case taicpu(p).opsize of
  2297. S_B:
  2298. if (taicpu(hp1).oper[0]^.val = $ff) then
  2299. begin
  2300. { Convert:
  2301. movb x, %regl movb x, %regl
  2302. andw ffh, %regw andl ffh, %regd
  2303. To:
  2304. movzbw x, %regd movzbl x, %regd
  2305. (Identical registers, just different sizes)
  2306. }
  2307. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2308. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2309. case taicpu(hp1).opsize of
  2310. S_W: NewSize := S_BW;
  2311. S_L: NewSize := S_BL;
  2312. {$ifdef x86_64}
  2313. S_Q: NewSize := S_BQ;
  2314. {$endif x86_64}
  2315. else
  2316. InternalError(2018011510);
  2317. end;
  2318. end
  2319. else
  2320. NewSize := S_NO;
  2321. S_W:
  2322. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2323. begin
  2324. { Convert:
  2325. movw x, %regw
  2326. andl ffffh, %regd
  2327. To:
  2328. movzwl x, %regd
  2329. (Identical registers, just different sizes)
  2330. }
  2331. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2332. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2333. case taicpu(hp1).opsize of
  2334. S_L: NewSize := S_WL;
  2335. {$ifdef x86_64}
  2336. S_Q: NewSize := S_WQ;
  2337. {$endif x86_64}
  2338. else
  2339. InternalError(2018011511);
  2340. end;
  2341. end
  2342. else
  2343. NewSize := S_NO;
  2344. else
  2345. NewSize := S_NO;
  2346. end;
  2347. if NewSize <> S_NO then
  2348. begin
  2349. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2350. { The actual optimization }
  2351. taicpu(p).opcode := A_MOVZX;
  2352. taicpu(p).changeopsize(NewSize);
  2353. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2354. { Safeguard if "and" is followed by a conditional command }
  2355. TransferUsedRegs(TmpUsedRegs);
  2356. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2357. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2358. begin
  2359. { At this point, the "and" command is effectively equivalent to
  2360. "test %reg,%reg". This will be handled separately by the
  2361. Peephole Optimizer. [Kit] }
  2362. DebugMsg(SPeepholeOptimization + PreMessage +
  2363. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2364. end
  2365. else
  2366. begin
  2367. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2368. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2369. RemoveInstruction(hp1);
  2370. end;
  2371. Result := True;
  2372. Exit;
  2373. end;
  2374. end;
  2375. end;
  2376. if (taicpu(hp1).opcode = A_OR) and
  2377. (taicpu(p).oper[1]^.typ = top_reg) and
  2378. MatchOperand(taicpu(p).oper[0]^, 0) and
  2379. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2380. begin
  2381. { mov 0, %reg
  2382. or ###,%reg
  2383. Change to (only if the flags are not used):
  2384. mov ###,%reg
  2385. }
  2386. TransferUsedRegs(TmpUsedRegs);
  2387. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2388. if not (RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs)) then
  2389. begin
  2390. {$ifdef x86_64}
  2391. { OR only supports 32-bit sign-extended constants for 64-bit
  2392. instructions, so compensate for this if the constant is
  2393. encoded as a value greater than or equal to 2^31 }
  2394. if (taicpu(hp1).opsize = S_Q) and
  2395. (taicpu(hp1).oper[0]^.typ = top_const) and
  2396. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2397. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2398. {$endif x86_64}
  2399. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2400. taicpu(hp1).opcode := A_MOV;
  2401. RemoveCurrentP(p, hp1);
  2402. Result := True;
  2403. Exit;
  2404. end;
  2405. end;
  2406. { Next instruction is also a MOV ? }
  2407. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2408. begin
  2409. if (taicpu(p).oper[1]^.typ = top_reg) and
  2410. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2411. begin
  2412. CurrentReg := taicpu(p).oper[1]^.reg;
  2413. TransferUsedRegs(TmpUsedRegs);
  2414. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2415. { we have
  2416. mov x, %treg
  2417. mov %treg, y
  2418. }
  2419. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2420. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2421. { we've got
  2422. mov x, %treg
  2423. mov %treg, y
  2424. with %treg is not used after }
  2425. case taicpu(p).oper[0]^.typ Of
  2426. { top_reg is covered by DeepMOVOpt }
  2427. top_const:
  2428. begin
  2429. { change
  2430. mov const, %treg
  2431. mov %treg, y
  2432. to
  2433. mov const, y
  2434. }
  2435. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2436. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2437. begin
  2438. if taicpu(hp1).oper[1]^.typ=top_reg then
  2439. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2440. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2441. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2442. RemoveInstruction(hp1);
  2443. Result:=true;
  2444. Exit;
  2445. end;
  2446. end;
  2447. top_ref:
  2448. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2449. begin
  2450. { change
  2451. mov mem, %treg
  2452. mov %treg, %reg
  2453. to
  2454. mov mem, %reg"
  2455. }
  2456. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2457. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2458. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2459. RemoveInstruction(hp1);
  2460. Result:=true;
  2461. Exit;
  2462. end;
  2463. else
  2464. ;
  2465. end
  2466. else
  2467. { %treg is used afterwards, but all eventualities
  2468. other than the first MOV instruction being a constant
  2469. are covered by DeepMOVOpt, so only check for that }
  2470. if (taicpu(p).oper[0]^.typ = top_const) and
  2471. (
  2472. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2473. not (cs_opt_size in current_settings.optimizerswitches) or
  2474. (taicpu(hp1).opsize = S_B)
  2475. ) and
  2476. (
  2477. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2478. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2479. ) then
  2480. begin
  2481. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2482. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2483. end;
  2484. end;
  2485. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2486. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2487. { mov reg1, mem1 or mov mem1, reg1
  2488. mov mem2, reg2 mov reg2, mem2}
  2489. begin
  2490. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2491. { mov reg1, mem1 or mov mem1, reg1
  2492. mov mem2, reg1 mov reg2, mem1}
  2493. begin
  2494. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2495. { Removes the second statement from
  2496. mov reg1, mem1/reg2
  2497. mov mem1/reg2, reg1 }
  2498. begin
  2499. if taicpu(p).oper[0]^.typ=top_reg then
  2500. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2501. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2502. RemoveInstruction(hp1);
  2503. Result:=true;
  2504. exit;
  2505. end
  2506. else
  2507. begin
  2508. TransferUsedRegs(TmpUsedRegs);
  2509. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2510. if (taicpu(p).oper[1]^.typ = top_ref) and
  2511. { mov reg1, mem1
  2512. mov mem2, reg1 }
  2513. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2514. GetNextInstruction(hp1, hp2) and
  2515. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2516. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2517. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2518. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2519. { change to
  2520. mov reg1, mem1 mov reg1, mem1
  2521. mov mem2, reg1 cmp reg1, mem2
  2522. cmp mem1, reg1
  2523. }
  2524. begin
  2525. RemoveInstruction(hp2);
  2526. taicpu(hp1).opcode := A_CMP;
  2527. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2528. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2529. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2530. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2531. end;
  2532. end;
  2533. end
  2534. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2535. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2536. begin
  2537. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2538. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2539. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2540. end
  2541. else
  2542. begin
  2543. TransferUsedRegs(TmpUsedRegs);
  2544. if GetNextInstruction(hp1, hp2) and
  2545. MatchOpType(taicpu(p),top_ref,top_reg) and
  2546. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2547. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2548. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2549. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2550. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2551. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2552. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2553. { mov mem1, %reg1
  2554. mov %reg1, mem2
  2555. mov mem2, reg2
  2556. to:
  2557. mov mem1, reg2
  2558. mov reg2, mem2}
  2559. begin
  2560. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2561. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2562. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2563. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2564. RemoveInstruction(hp2);
  2565. end
  2566. {$ifdef i386}
  2567. { this is enabled for i386 only, as the rules to create the reg sets below
  2568. are too complicated for x86-64, so this makes this code too error prone
  2569. on x86-64
  2570. }
  2571. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2572. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2573. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2574. { mov mem1, reg1 mov mem1, reg1
  2575. mov reg1, mem2 mov reg1, mem2
  2576. mov mem2, reg2 mov mem2, reg1
  2577. to: to:
  2578. mov mem1, reg1 mov mem1, reg1
  2579. mov mem1, reg2 mov reg1, mem2
  2580. mov reg1, mem2
  2581. or (if mem1 depends on reg1
  2582. and/or if mem2 depends on reg2)
  2583. to:
  2584. mov mem1, reg1
  2585. mov reg1, mem2
  2586. mov reg1, reg2
  2587. }
  2588. begin
  2589. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  2590. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  2591. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  2592. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  2593. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2594. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  2595. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2596. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  2597. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  2598. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2599. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  2600. end
  2601. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  2602. begin
  2603. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  2604. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2605. end
  2606. else
  2607. begin
  2608. RemoveInstruction(hp2);
  2609. end
  2610. {$endif i386}
  2611. ;
  2612. end;
  2613. end
  2614. { movl [mem1],reg1
  2615. movl [mem1],reg2
  2616. to
  2617. movl [mem1],reg1
  2618. movl reg1,reg2
  2619. }
  2620. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  2621. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2622. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2623. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2624. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2625. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2626. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2627. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2628. begin
  2629. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2630. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2631. end;
  2632. { movl const1,[mem1]
  2633. movl [mem1],reg1
  2634. to
  2635. movl const1,reg1
  2636. movl reg1,[mem1]
  2637. }
  2638. if MatchOpType(Taicpu(p),top_const,top_ref) and
  2639. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  2640. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2641. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  2642. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  2643. begin
  2644. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2645. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  2646. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  2647. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  2648. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  2649. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  2650. Result:=true;
  2651. exit;
  2652. end;
  2653. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  2654. end;
  2655. { search further than the next instruction for a mov }
  2656. if
  2657. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  2658. (taicpu(p).oper[1]^.typ = top_reg) and
  2659. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  2660. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  2661. begin
  2662. { we work with hp2 here, so hp1 can be still used later on when
  2663. checking for GetNextInstruction_p }
  2664. hp3 := hp1;
  2665. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  2666. CrossJump := False;
  2667. while GetNextInstructionUsingRegCond(hp3,hp2,taicpu(p).oper[1]^.reg,CrossJump) and
  2668. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  2669. (hp2.typ=ait_instruction) do
  2670. begin
  2671. case taicpu(hp2).opcode of
  2672. A_MOV:
  2673. if MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^.reg) and
  2674. ((taicpu(p).oper[0]^.typ=top_const) or
  2675. ((taicpu(p).oper[0]^.typ=top_reg) and
  2676. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  2677. )
  2678. ) then
  2679. begin
  2680. { we have
  2681. mov x, %treg
  2682. mov %treg, y
  2683. }
  2684. TransferUsedRegs(TmpUsedRegs);
  2685. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2686. { We don't need to call UpdateUsedRegs for every instruction between
  2687. p and hp2 because the register we're concerned about will not
  2688. become deallocated (otherwise GetNextInstructionUsingReg would
  2689. have stopped at an earlier instruction). [Kit] }
  2690. TempRegUsed :=
  2691. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  2692. RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) or
  2693. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1);
  2694. case taicpu(p).oper[0]^.typ Of
  2695. top_reg:
  2696. begin
  2697. { change
  2698. mov %reg, %treg
  2699. mov %treg, y
  2700. to
  2701. mov %reg, y
  2702. }
  2703. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  2704. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2705. if taicpu(hp2).oper[1]^.reg = CurrentReg then
  2706. begin
  2707. { %reg = y - remove hp2 completely (doing it here instead of relying on
  2708. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  2709. if TempRegUsed then
  2710. begin
  2711. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  2712. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2713. { Set the start of the next GetNextInstructionUsingRegCond search
  2714. to start at the entry right before hp2 (which is about to be removed) }
  2715. hp3 := tai(hp2.Previous);
  2716. RemoveInstruction(hp2);
  2717. { See if there's more we can optimise }
  2718. Continue;
  2719. end
  2720. else
  2721. begin
  2722. RemoveInstruction(hp2);
  2723. { We can remove the original MOV too }
  2724. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  2725. RemoveCurrentP(p, hp1);
  2726. Result:=true;
  2727. Exit;
  2728. end;
  2729. end
  2730. else
  2731. begin
  2732. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2733. taicpu(hp2).loadReg(0, CurrentReg);
  2734. if TempRegUsed then
  2735. begin
  2736. { Don't remove the first instruction if the temporary register is in use }
  2737. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  2738. { No need to set Result to True. If there's another instruction later on
  2739. that can be optimised, it will be detected when the main Pass 1 loop
  2740. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2741. end
  2742. else
  2743. begin
  2744. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  2745. RemoveCurrentP(p, hp1);
  2746. Result:=true;
  2747. Exit;
  2748. end;
  2749. end;
  2750. end;
  2751. top_const:
  2752. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  2753. begin
  2754. { change
  2755. mov const, %treg
  2756. mov %treg, y
  2757. to
  2758. mov const, y
  2759. }
  2760. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  2761. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2762. begin
  2763. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2764. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  2765. if TempRegUsed then
  2766. begin
  2767. { Don't remove the first instruction if the temporary register is in use }
  2768. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  2769. { No need to set Result to True. If there's another instruction later on
  2770. that can be optimised, it will be detected when the main Pass 1 loop
  2771. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2772. end
  2773. else
  2774. begin
  2775. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  2776. RemoveCurrentP(p, hp1);
  2777. Result:=true;
  2778. Exit;
  2779. end;
  2780. end;
  2781. end;
  2782. else
  2783. Internalerror(2019103001);
  2784. end;
  2785. end;
  2786. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  2787. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  2788. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  2789. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2790. begin
  2791. {
  2792. Change from:
  2793. mov ###, %reg
  2794. ...
  2795. movs/z %reg,%reg (Same register, just different sizes)
  2796. To:
  2797. movs/z ###, %reg (Longer version)
  2798. ...
  2799. (remove)
  2800. }
  2801. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  2802. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  2803. { Keep the first instruction as mov if ### is a constant }
  2804. if taicpu(p).oper[0]^.typ = top_const then
  2805. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  2806. else
  2807. begin
  2808. taicpu(p).opcode := taicpu(hp2).opcode;
  2809. taicpu(p).opsize := taicpu(hp2).opsize;
  2810. end;
  2811. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  2812. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  2813. RemoveInstruction(hp2);
  2814. Result := True;
  2815. Exit;
  2816. end;
  2817. else
  2818. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2819. begin
  2820. CurrentReg := taicpu(p).oper[1]^.reg;
  2821. TransferUsedRegs(TmpUsedRegs);
  2822. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2823. if
  2824. not RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) and
  2825. not RegModifiedBetween(taicpu(p).oper[0]^.reg, hp1, hp2) and
  2826. DeepMovOpt(taicpu(p), taicpu(hp2)) then
  2827. begin
  2828. { Just in case something didn't get modified (e.g. an
  2829. implicit register) }
  2830. if not RegReadByInstruction(CurrentReg, hp2) and
  2831. { If a conditional jump was crossed, do not delete
  2832. the original MOV no matter what }
  2833. not CrossJump then
  2834. begin
  2835. TransferUsedRegs(TmpUsedRegs);
  2836. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2837. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2838. if
  2839. { Make sure the original register isn't still present
  2840. and has been written to (e.g. with SHRX) }
  2841. RegLoadedWithNewValue(CurrentReg, hp2) or
  2842. not RegUsedAfterInstruction(CurrentReg, hp2, TmpUsedRegs) then
  2843. begin
  2844. { We can remove the original MOV }
  2845. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  2846. RemoveCurrentp(p, hp1);
  2847. Result := True;
  2848. Exit;
  2849. end
  2850. else
  2851. begin
  2852. { See if there's more we can optimise }
  2853. hp3 := hp2;
  2854. Continue;
  2855. end;
  2856. end;
  2857. end;
  2858. end;
  2859. end;
  2860. { Break out of the while loop under normal circumstances }
  2861. Break;
  2862. end;
  2863. end;
  2864. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  2865. (taicpu(p).oper[1]^.typ = top_reg) and
  2866. (taicpu(p).opsize = S_L) and
  2867. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  2868. (taicpu(hp2).opcode = A_AND) and
  2869. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  2870. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2871. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  2872. ) then
  2873. begin
  2874. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  2875. begin
  2876. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  2877. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  2878. begin
  2879. { Optimize out:
  2880. mov x, %reg
  2881. and ffffffffh, %reg
  2882. }
  2883. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  2884. RemoveInstruction(hp2);
  2885. Result:=true;
  2886. exit;
  2887. end;
  2888. end;
  2889. end;
  2890. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  2891. x >= RetOffset) as it doesn't do anything (it writes either to a
  2892. parameter or to the temporary storage room for the function
  2893. result)
  2894. }
  2895. if IsExitCode(hp1) and
  2896. (taicpu(p).oper[1]^.typ = top_ref) and
  2897. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  2898. (
  2899. (
  2900. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  2901. not (
  2902. assigned(current_procinfo.procdef.funcretsym) and
  2903. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  2904. )
  2905. ) or
  2906. { Also discard writes to the stack that are below the base pointer,
  2907. as this is temporary storage rather than a function result on the
  2908. stack, say. }
  2909. (
  2910. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  2911. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  2912. )
  2913. ) then
  2914. begin
  2915. RemoveCurrentp(p, hp1);
  2916. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  2917. RemoveLastDeallocForFuncRes(p);
  2918. Result:=true;
  2919. exit;
  2920. end;
  2921. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  2922. begin
  2923. if MatchOpType(taicpu(p),top_reg,top_ref) and
  2924. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2925. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2926. begin
  2927. { change
  2928. mov reg1, mem1
  2929. test/cmp x, mem1
  2930. to
  2931. mov reg1, mem1
  2932. test/cmp x, reg1
  2933. }
  2934. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  2935. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  2936. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2937. Result := True;
  2938. Exit;
  2939. end;
  2940. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2941. { The x86 assemblers have difficulty comparing values against absolute addresses }
  2942. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  2943. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  2944. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  2945. (
  2946. (
  2947. (taicpu(hp1).opcode = A_TEST)
  2948. ) or (
  2949. (taicpu(hp1).opcode = A_CMP) and
  2950. { A sanity check more than anything }
  2951. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  2952. )
  2953. ) then
  2954. begin
  2955. { change
  2956. mov mem, %reg
  2957. cmp/test x, %reg / test %reg,%reg
  2958. (reg deallocated)
  2959. to
  2960. cmp/test x, mem / cmp 0, mem
  2961. }
  2962. TransferUsedRegs(TmpUsedRegs);
  2963. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2964. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2965. begin
  2966. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  2967. if (taicpu(hp1).opcode = A_TEST) and
  2968. (
  2969. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  2970. MatchOperand(taicpu(hp1).oper[0]^, -1)
  2971. ) then
  2972. begin
  2973. taicpu(hp1).opcode := A_CMP;
  2974. taicpu(hp1).loadconst(0, 0);
  2975. end;
  2976. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  2977. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  2978. RemoveCurrentP(p, hp1);
  2979. Result := True;
  2980. Exit;
  2981. end;
  2982. end;
  2983. end;
  2984. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  2985. { If the flags register is in use, don't change the instruction to an
  2986. ADD otherwise this will scramble the flags. [Kit] }
  2987. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  2988. begin
  2989. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  2990. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  2991. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  2992. ) or
  2993. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  2994. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  2995. )
  2996. ) then
  2997. { mov reg1,ref
  2998. lea reg2,[reg1,reg2]
  2999. to
  3000. add reg2,ref}
  3001. begin
  3002. TransferUsedRegs(TmpUsedRegs);
  3003. { reg1 may not be used afterwards }
  3004. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3005. begin
  3006. Taicpu(hp1).opcode:=A_ADD;
  3007. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3008. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3009. RemoveCurrentp(p, hp1);
  3010. result:=true;
  3011. exit;
  3012. end;
  3013. end;
  3014. { If the LEA instruction can be converted into an arithmetic instruction,
  3015. it may be possible to then fold it in the next optimisation, otherwise
  3016. there's nothing more that can be optimised here. }
  3017. if not ConvertLEA(taicpu(hp1)) then
  3018. Exit;
  3019. end;
  3020. if (taicpu(p).oper[1]^.typ = top_reg) and
  3021. (hp1.typ = ait_instruction) and
  3022. GetNextInstruction(hp1, hp2) and
  3023. MatchInstruction(hp2,A_MOV,[]) and
  3024. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3025. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3026. (
  3027. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3028. {$ifdef x86_64}
  3029. or
  3030. (
  3031. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3032. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3033. )
  3034. {$endif x86_64}
  3035. ) then
  3036. begin
  3037. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3038. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3039. { change movsX/movzX reg/ref, reg2
  3040. add/sub/or/... reg3/$const, reg2
  3041. mov reg2 reg/ref
  3042. dealloc reg2
  3043. to
  3044. add/sub/or/... reg3/$const, reg/ref }
  3045. begin
  3046. TransferUsedRegs(TmpUsedRegs);
  3047. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3048. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3049. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3050. begin
  3051. { by example:
  3052. movswl %si,%eax movswl %si,%eax p
  3053. decl %eax addl %edx,%eax hp1
  3054. movw %ax,%si movw %ax,%si hp2
  3055. ->
  3056. movswl %si,%eax movswl %si,%eax p
  3057. decw %eax addw %edx,%eax hp1
  3058. movw %ax,%si movw %ax,%si hp2
  3059. }
  3060. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3061. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3062. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3063. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3064. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3065. {
  3066. ->
  3067. movswl %si,%eax movswl %si,%eax p
  3068. decw %si addw %dx,%si hp1
  3069. movw %ax,%si movw %ax,%si hp2
  3070. }
  3071. case taicpu(hp1).ops of
  3072. 1:
  3073. begin
  3074. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3075. if taicpu(hp1).oper[0]^.typ=top_reg then
  3076. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3077. end;
  3078. 2:
  3079. begin
  3080. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3081. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3082. (taicpu(hp1).opcode<>A_SHL) and
  3083. (taicpu(hp1).opcode<>A_SHR) and
  3084. (taicpu(hp1).opcode<>A_SAR) then
  3085. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3086. end;
  3087. else
  3088. internalerror(2008042701);
  3089. end;
  3090. {
  3091. ->
  3092. decw %si addw %dx,%si p
  3093. }
  3094. RemoveInstruction(hp2);
  3095. RemoveCurrentP(p, hp1);
  3096. Result:=True;
  3097. Exit;
  3098. end;
  3099. end;
  3100. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3101. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3102. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3103. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3104. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3105. )
  3106. {$ifdef i386}
  3107. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3108. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3109. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3110. {$endif i386}
  3111. then
  3112. { change movsX/movzX reg/ref, reg2
  3113. add/sub/or/... regX/$const, reg2
  3114. mov reg2, reg3
  3115. dealloc reg2
  3116. to
  3117. movsX/movzX reg/ref, reg3
  3118. add/sub/or/... reg3/$const, reg3
  3119. }
  3120. begin
  3121. TransferUsedRegs(TmpUsedRegs);
  3122. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3123. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3124. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3125. begin
  3126. { by example:
  3127. movswl %si,%eax movswl %si,%eax p
  3128. decl %eax addl %edx,%eax hp1
  3129. movw %ax,%si movw %ax,%si hp2
  3130. ->
  3131. movswl %si,%eax movswl %si,%eax p
  3132. decw %eax addw %edx,%eax hp1
  3133. movw %ax,%si movw %ax,%si hp2
  3134. }
  3135. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3136. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3137. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3138. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3139. { limit size of constants as well to avoid assembler errors, but
  3140. check opsize to avoid overflow when left shifting the 1 }
  3141. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3142. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3143. {$ifdef x86_64}
  3144. { Be careful of, for example:
  3145. movl %reg1,%reg2
  3146. addl %reg3,%reg2
  3147. movq %reg2,%reg4
  3148. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3149. }
  3150. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3151. begin
  3152. taicpu(hp2).changeopsize(S_L);
  3153. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3154. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3155. end;
  3156. {$endif x86_64}
  3157. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3158. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3159. if taicpu(p).oper[0]^.typ=top_reg then
  3160. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3161. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3162. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3163. {
  3164. ->
  3165. movswl %si,%eax movswl %si,%eax p
  3166. decw %si addw %dx,%si hp1
  3167. movw %ax,%si movw %ax,%si hp2
  3168. }
  3169. case taicpu(hp1).ops of
  3170. 1:
  3171. begin
  3172. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3173. if taicpu(hp1).oper[0]^.typ=top_reg then
  3174. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3175. end;
  3176. 2:
  3177. begin
  3178. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3179. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3180. (taicpu(hp1).opcode<>A_SHL) and
  3181. (taicpu(hp1).opcode<>A_SHR) and
  3182. (taicpu(hp1).opcode<>A_SAR) then
  3183. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3184. end;
  3185. else
  3186. internalerror(2018111801);
  3187. end;
  3188. {
  3189. ->
  3190. decw %si addw %dx,%si p
  3191. }
  3192. RemoveInstruction(hp2);
  3193. end;
  3194. end;
  3195. end;
  3196. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3197. GetNextInstruction(hp1, hp2) and
  3198. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3199. MatchOperand(Taicpu(p).oper[0]^,0) and
  3200. (Taicpu(p).oper[1]^.typ = top_reg) and
  3201. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3202. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3203. { mov reg1,0
  3204. bts reg1,operand1 --> mov reg1,operand2
  3205. or reg1,operand2 bts reg1,operand1}
  3206. begin
  3207. Taicpu(hp2).opcode:=A_MOV;
  3208. asml.remove(hp1);
  3209. insertllitem(hp2,hp2.next,hp1);
  3210. RemoveCurrentp(p, hp1);
  3211. Result:=true;
  3212. exit;
  3213. end;
  3214. {$ifdef x86_64}
  3215. { Convert:
  3216. movq x(ref),%reg64
  3217. shrq y,%reg64
  3218. To:
  3219. movq x+4(ref),%reg32
  3220. shrq y-32,%reg32 (Remove if y = 32)
  3221. }
  3222. if (taicpu(p).opsize = S_Q) and
  3223. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3224. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3225. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3226. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3227. (taicpu(hp1).oper[0]^.val >= 32) and
  3228. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3229. begin
  3230. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3231. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3232. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3233. { Convert to 32-bit }
  3234. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3235. taicpu(p).opsize := S_L;
  3236. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3237. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3238. if (taicpu(hp1).oper[0]^.val = 32) then
  3239. begin
  3240. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3241. RemoveInstruction(hp1);
  3242. end
  3243. else
  3244. begin
  3245. { This will potentially open up more arithmetic operations since
  3246. the peephole optimizer now has a big hint that only the lower
  3247. 32 bits are currently in use (and opcodes are smaller in size) }
  3248. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3249. taicpu(hp1).opsize := S_L;
  3250. Dec(taicpu(hp1).oper[0]^.val, 32);
  3251. DebugMsg(SPeepholeOptimization + PreMessage +
  3252. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3253. end;
  3254. Result := True;
  3255. Exit;
  3256. end;
  3257. {$endif x86_64}
  3258. end;
  3259. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3260. var
  3261. hp1 : tai;
  3262. begin
  3263. Result:=false;
  3264. if taicpu(p).ops <> 2 then
  3265. exit;
  3266. if GetNextInstruction(p,hp1) and
  3267. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3268. (taicpu(hp1).ops = 2) then
  3269. begin
  3270. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3271. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3272. { movXX reg1, mem1 or movXX mem1, reg1
  3273. movXX mem2, reg2 movXX reg2, mem2}
  3274. begin
  3275. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3276. { movXX reg1, mem1 or movXX mem1, reg1
  3277. movXX mem2, reg1 movXX reg2, mem1}
  3278. begin
  3279. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3280. begin
  3281. { Removes the second statement from
  3282. movXX reg1, mem1/reg2
  3283. movXX mem1/reg2, reg1
  3284. }
  3285. if taicpu(p).oper[0]^.typ=top_reg then
  3286. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3287. { Removes the second statement from
  3288. movXX mem1/reg1, reg2
  3289. movXX reg2, mem1/reg1
  3290. }
  3291. if (taicpu(p).oper[1]^.typ=top_reg) and
  3292. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3293. begin
  3294. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3295. RemoveInstruction(hp1);
  3296. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3297. end
  3298. else
  3299. begin
  3300. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3301. RemoveInstruction(hp1);
  3302. end;
  3303. Result:=true;
  3304. exit;
  3305. end
  3306. end;
  3307. end;
  3308. end;
  3309. end;
  3310. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3311. var
  3312. hp1 : tai;
  3313. begin
  3314. result:=false;
  3315. { replace
  3316. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3317. MovX %mreg2,%mreg1
  3318. dealloc %mreg2
  3319. by
  3320. <Op>X %mreg2,%mreg1
  3321. ?
  3322. }
  3323. if GetNextInstruction(p,hp1) and
  3324. { we mix single and double opperations here because we assume that the compiler
  3325. generates vmovapd only after double operations and vmovaps only after single operations }
  3326. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3327. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3328. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3329. (taicpu(p).oper[0]^.typ=top_reg) then
  3330. begin
  3331. TransferUsedRegs(TmpUsedRegs);
  3332. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3333. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3334. begin
  3335. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3336. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3337. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3338. RemoveInstruction(hp1);
  3339. result:=true;
  3340. end;
  3341. end;
  3342. end;
  3343. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3344. var
  3345. hp1, p_label, p_dist, hp1_dist: tai;
  3346. JumpLabel, JumpLabel_dist: TAsmLabel;
  3347. begin
  3348. Result := False;
  3349. if (taicpu(p).oper[1]^.typ = top_reg) then
  3350. begin
  3351. if GetNextInstruction(p, hp1) and
  3352. MatchInstruction(hp1,A_MOV,[]) and
  3353. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  3354. (
  3355. (taicpu(p).oper[0]^.typ <> top_reg) or
  3356. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  3357. ) then
  3358. begin
  3359. { If we have something like:
  3360. test %reg1,%reg1
  3361. mov 0,%reg2
  3362. And no registers are shared (the two %reg1's can be different, as
  3363. long as neither of them are also %reg2), move the MOV command to
  3364. before the comparison as this means it can be optimised without
  3365. worrying about the FLAGS register. (This combination is generated
  3366. by "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  3367. }
  3368. SwapMovCmp(p, hp1);
  3369. Result := True;
  3370. Exit;
  3371. end;
  3372. { Search for:
  3373. test %reg,%reg
  3374. j(c1) @lbl1
  3375. ...
  3376. @lbl:
  3377. test %reg,%reg (same register)
  3378. j(c2) @lbl2
  3379. If c2 is a subset of c1, change to:
  3380. test %reg,%reg
  3381. j(c1) @lbl2
  3382. (@lbl1 may become a dead label as a result)
  3383. }
  3384. if (taicpu(p).oper[0]^.typ = top_reg) and
  3385. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  3386. MatchInstruction(hp1, A_JCC, []) and
  3387. IsJumpToLabel(taicpu(hp1)) then
  3388. begin
  3389. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  3390. p_label := nil;
  3391. if Assigned(JumpLabel) then
  3392. p_label := getlabelwithsym(JumpLabel);
  3393. if Assigned(p_label) and
  3394. GetNextInstruction(p_label, p_dist) and
  3395. MatchInstruction(p_dist, A_TEST, []) and
  3396. { It's fine if the second test uses smaller sub-registers }
  3397. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  3398. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  3399. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  3400. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  3401. GetNextInstruction(p_dist, hp1_dist) and
  3402. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  3403. begin
  3404. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  3405. if JumpLabel = JumpLabel_dist then
  3406. { This is an infinite loop }
  3407. Exit;
  3408. { Best optimisation when the first condition is a subset (or equal) of the second }
  3409. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  3410. begin
  3411. { Any registers used here will already be allocated }
  3412. if Assigned(JumpLabel_dist) then
  3413. JumpLabel_dist.IncRefs;
  3414. if Assigned(JumpLabel) then
  3415. JumpLabel.DecRefs;
  3416. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  3417. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  3418. Result := True;
  3419. Exit;
  3420. end;
  3421. end;
  3422. end;
  3423. end;
  3424. end;
  3425. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  3426. var
  3427. hp1 : tai;
  3428. begin
  3429. result:=false;
  3430. { replace
  3431. addX const,%reg1
  3432. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  3433. dealloc %reg1
  3434. by
  3435. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  3436. }
  3437. if MatchOpType(taicpu(p),top_const,top_reg) and
  3438. GetNextInstruction(p,hp1) and
  3439. MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3440. ((taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base) or
  3441. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index)) then
  3442. begin
  3443. TransferUsedRegs(TmpUsedRegs);
  3444. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3445. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3446. begin
  3447. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  3448. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base then
  3449. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  3450. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index then
  3451. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3452. RemoveCurrentP(p);
  3453. result:=true;
  3454. end;
  3455. end;
  3456. end;
  3457. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  3458. var
  3459. hp1: tai;
  3460. ref: Integer;
  3461. saveref: treference;
  3462. TempReg: TRegister;
  3463. Multiple: TCGInt;
  3464. begin
  3465. Result:=false;
  3466. { removes seg register prefixes from LEA operations, as they
  3467. don't do anything}
  3468. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  3469. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  3470. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3471. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  3472. (
  3473. { do not mess with leas accessing the stack pointer
  3474. unless it's a null operation }
  3475. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  3476. (
  3477. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  3478. (taicpu(p).oper[0]^.ref^.offset = 0)
  3479. )
  3480. ) and
  3481. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  3482. begin
  3483. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  3484. begin
  3485. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  3486. begin
  3487. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  3488. taicpu(p).oper[1]^.reg);
  3489. InsertLLItem(p.previous,p.next, hp1);
  3490. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  3491. p.free;
  3492. p:=hp1;
  3493. end
  3494. else
  3495. begin
  3496. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  3497. RemoveCurrentP(p);
  3498. end;
  3499. Result:=true;
  3500. exit;
  3501. end
  3502. else if (
  3503. { continue to use lea to adjust the stack pointer,
  3504. it is the recommended way, but only if not optimizing for size }
  3505. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  3506. (cs_opt_size in current_settings.optimizerswitches)
  3507. ) and
  3508. { If the flags register is in use, don't change the instruction
  3509. to an ADD otherwise this will scramble the flags. [Kit] }
  3510. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  3511. ConvertLEA(taicpu(p)) then
  3512. begin
  3513. Result:=true;
  3514. exit;
  3515. end;
  3516. end;
  3517. if GetNextInstruction(p,hp1) and
  3518. (hp1.typ=ait_instruction) then
  3519. begin
  3520. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  3521. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3522. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  3523. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  3524. begin
  3525. TransferUsedRegs(TmpUsedRegs);
  3526. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3527. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3528. begin
  3529. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3530. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  3531. RemoveInstruction(hp1);
  3532. result:=true;
  3533. exit;
  3534. end;
  3535. end;
  3536. { changes
  3537. lea <ref1>, reg1
  3538. <op> ...,<ref. with reg1>,...
  3539. to
  3540. <op> ...,<ref1>,... }
  3541. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  3542. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  3543. not(MatchInstruction(hp1,A_LEA,[])) then
  3544. begin
  3545. { find a reference which uses reg1 }
  3546. 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
  3547. ref:=0
  3548. 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
  3549. ref:=1
  3550. else
  3551. ref:=-1;
  3552. if (ref<>-1) and
  3553. { reg1 must be either the base or the index }
  3554. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  3555. begin
  3556. { reg1 can be removed from the reference }
  3557. saveref:=taicpu(hp1).oper[ref]^.ref^;
  3558. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  3559. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  3560. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  3561. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  3562. else
  3563. Internalerror(2019111201);
  3564. { check if the can insert all data of the lea into the second instruction }
  3565. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3566. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  3567. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  3568. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  3569. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  3570. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3571. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  3572. {$ifdef x86_64}
  3573. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  3574. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  3575. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  3576. )
  3577. {$endif x86_64}
  3578. then
  3579. begin
  3580. { reg1 might not used by the second instruction after it is remove from the reference }
  3581. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  3582. begin
  3583. TransferUsedRegs(TmpUsedRegs);
  3584. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3585. { reg1 is not updated so it might not be used afterwards }
  3586. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3587. begin
  3588. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  3589. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  3590. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3591. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3592. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3593. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  3594. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  3595. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  3596. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  3597. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  3598. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3599. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3600. RemoveCurrentP(p, hp1);
  3601. result:=true;
  3602. exit;
  3603. end
  3604. end;
  3605. end;
  3606. { recover }
  3607. taicpu(hp1).oper[ref]^.ref^:=saveref;
  3608. end;
  3609. end;
  3610. end;
  3611. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  3612. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  3613. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  3614. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  3615. begin
  3616. { Check common LEA/LEA conditions }
  3617. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3618. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  3619. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  3620. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  3621. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  3622. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  3623. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  3624. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  3625. (
  3626. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  3627. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  3628. ) and (
  3629. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  3630. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3631. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  3632. ) then
  3633. begin
  3634. { changes
  3635. lea (regX,scale), reg1
  3636. lea offset(reg1,reg1), reg1
  3637. to
  3638. lea offset(regX,scale*2), reg1
  3639. and
  3640. lea (regX,scale1), reg1
  3641. lea offset(reg1,scale2), reg1
  3642. to
  3643. lea offset(regX,scale1*scale2), reg1
  3644. ... so long as the final scale does not exceed 8
  3645. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  3646. }
  3647. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  3648. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3649. (
  3650. (
  3651. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  3652. ) or (
  3653. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3654. (
  3655. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  3656. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  3657. )
  3658. )
  3659. ) and (
  3660. (
  3661. { lea (reg1,scale2), reg1 variant }
  3662. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  3663. (
  3664. (
  3665. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  3666. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  3667. ) or (
  3668. { lea (regX,regX), reg1 variant }
  3669. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3670. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  3671. )
  3672. )
  3673. ) or (
  3674. { lea (reg1,reg1), reg1 variant }
  3675. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  3676. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  3677. )
  3678. ) then
  3679. begin
  3680. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  3681. { Make everything homogeneous to make calculations easier }
  3682. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  3683. begin
  3684. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  3685. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  3686. taicpu(p).oper[0]^.ref^.scalefactor := 2
  3687. else
  3688. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  3689. taicpu(p).oper[0]^.ref^.base := NR_NO;
  3690. end;
  3691. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  3692. begin
  3693. { Just to prevent miscalculations }
  3694. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  3695. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  3696. else
  3697. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  3698. end
  3699. else
  3700. begin
  3701. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  3702. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  3703. end;
  3704. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  3705. RemoveCurrentP(p);
  3706. result:=true;
  3707. exit;
  3708. end
  3709. { changes
  3710. lea offset1(regX), reg1
  3711. lea offset2(reg1), reg1
  3712. to
  3713. lea offset1+offset2(regX), reg1 }
  3714. else if
  3715. (
  3716. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3717. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  3718. ) or (
  3719. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  3720. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  3721. (
  3722. (
  3723. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3724. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  3725. ) or (
  3726. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3727. (
  3728. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3729. (
  3730. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3731. (
  3732. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  3733. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  3734. )
  3735. )
  3736. )
  3737. )
  3738. )
  3739. ) then
  3740. begin
  3741. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  3742. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  3743. begin
  3744. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  3745. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3746. { if the register is used as index and base, we have to increase for base as well
  3747. and adapt base }
  3748. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  3749. begin
  3750. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3751. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3752. end;
  3753. end
  3754. else
  3755. begin
  3756. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3757. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3758. end;
  3759. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3760. begin
  3761. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  3762. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3763. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3764. end;
  3765. RemoveCurrentP(p);
  3766. result:=true;
  3767. exit;
  3768. end;
  3769. end;
  3770. { Change:
  3771. leal/q $x(%reg1),%reg2
  3772. ...
  3773. shll/q $y,%reg2
  3774. To:
  3775. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  3776. }
  3777. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  3778. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3779. (taicpu(hp1).oper[0]^.val <= 3) then
  3780. begin
  3781. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  3782. TransferUsedRegs(TmpUsedRegs);
  3783. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3784. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  3785. if
  3786. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  3787. (this works even if scalefactor is zero) }
  3788. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  3789. { Ensure offset doesn't go out of bounds }
  3790. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  3791. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  3792. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  3793. (
  3794. (
  3795. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  3796. (
  3797. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3798. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  3799. (
  3800. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  3801. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3802. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  3803. )
  3804. )
  3805. ) or (
  3806. (
  3807. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  3808. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  3809. ) and
  3810. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  3811. )
  3812. ) then
  3813. begin
  3814. repeat
  3815. with taicpu(p).oper[0]^.ref^ do
  3816. begin
  3817. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  3818. if index = base then
  3819. begin
  3820. if Multiple > 4 then
  3821. { Optimisation will no longer work because resultant
  3822. scale factor will exceed 8 }
  3823. Break;
  3824. base := NR_NO;
  3825. scalefactor := 2;
  3826. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  3827. end
  3828. else if (base <> NR_NO) and (base <> NR_INVALID) then
  3829. begin
  3830. { Scale factor only works on the index register }
  3831. index := base;
  3832. base := NR_NO;
  3833. end;
  3834. { For safety }
  3835. if scalefactor <= 1 then
  3836. begin
  3837. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  3838. scalefactor := Multiple;
  3839. end
  3840. else
  3841. begin
  3842. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  3843. scalefactor := scalefactor * Multiple;
  3844. end;
  3845. offset := offset * Multiple;
  3846. end;
  3847. RemoveInstruction(hp1);
  3848. Result := True;
  3849. Exit;
  3850. { This repeat..until loop exists for the benefit of Break }
  3851. until True;
  3852. end;
  3853. end;
  3854. end;
  3855. end;
  3856. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  3857. var
  3858. hp1 : tai;
  3859. begin
  3860. DoSubAddOpt := False;
  3861. if GetLastInstruction(p, hp1) and
  3862. (hp1.typ = ait_instruction) and
  3863. (taicpu(hp1).opsize = taicpu(p).opsize) then
  3864. case taicpu(hp1).opcode Of
  3865. A_DEC:
  3866. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  3867. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3868. begin
  3869. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  3870. RemoveInstruction(hp1);
  3871. end;
  3872. A_SUB:
  3873. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3874. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3875. begin
  3876. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  3877. RemoveInstruction(hp1);
  3878. end;
  3879. A_ADD:
  3880. begin
  3881. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3882. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3883. begin
  3884. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  3885. RemoveInstruction(hp1);
  3886. if (taicpu(p).oper[0]^.val = 0) then
  3887. begin
  3888. hp1 := tai(p.next);
  3889. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  3890. if not GetLastInstruction(hp1, p) then
  3891. p := hp1;
  3892. DoSubAddOpt := True;
  3893. end
  3894. end;
  3895. end;
  3896. else
  3897. ;
  3898. end;
  3899. end;
  3900. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  3901. {$ifdef i386}
  3902. var
  3903. hp1 : tai;
  3904. {$endif i386}
  3905. begin
  3906. Result:=false;
  3907. { * change "subl $2, %esp; pushw x" to "pushl x"}
  3908. { * change "sub/add const1, reg" or "dec reg" followed by
  3909. "sub const2, reg" to one "sub ..., reg" }
  3910. if MatchOpType(taicpu(p),top_const,top_reg) then
  3911. begin
  3912. {$ifdef i386}
  3913. if (taicpu(p).oper[0]^.val = 2) and
  3914. (taicpu(p).oper[1]^.reg = NR_ESP) and
  3915. { Don't do the sub/push optimization if the sub }
  3916. { comes from setting up the stack frame (JM) }
  3917. (not(GetLastInstruction(p,hp1)) or
  3918. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  3919. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  3920. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  3921. begin
  3922. hp1 := tai(p.next);
  3923. while Assigned(hp1) and
  3924. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  3925. not RegReadByInstruction(NR_ESP,hp1) and
  3926. not RegModifiedByInstruction(NR_ESP,hp1) do
  3927. hp1 := tai(hp1.next);
  3928. if Assigned(hp1) and
  3929. MatchInstruction(hp1,A_PUSH,[S_W]) then
  3930. begin
  3931. taicpu(hp1).changeopsize(S_L);
  3932. if taicpu(hp1).oper[0]^.typ=top_reg then
  3933. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  3934. hp1 := tai(p.next);
  3935. RemoveCurrentp(p, hp1);
  3936. Result:=true;
  3937. exit;
  3938. end;
  3939. end;
  3940. {$endif i386}
  3941. if DoSubAddOpt(p) then
  3942. Result:=true;
  3943. end;
  3944. end;
  3945. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  3946. var
  3947. TmpBool1,TmpBool2 : Boolean;
  3948. tmpref : treference;
  3949. hp1,hp2: tai;
  3950. mask: tcgint;
  3951. begin
  3952. Result:=false;
  3953. { All these optimisations work on "shl/sal const,%reg" }
  3954. if not MatchOpType(taicpu(p),top_const,top_reg) then
  3955. Exit;
  3956. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3957. (taicpu(p).oper[0]^.val <= 3) then
  3958. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  3959. begin
  3960. { should we check the next instruction? }
  3961. TmpBool1 := True;
  3962. { have we found an add/sub which could be
  3963. integrated in the lea? }
  3964. TmpBool2 := False;
  3965. reference_reset(tmpref,2,[]);
  3966. TmpRef.index := taicpu(p).oper[1]^.reg;
  3967. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  3968. while TmpBool1 and
  3969. GetNextInstruction(p, hp1) and
  3970. (tai(hp1).typ = ait_instruction) and
  3971. ((((taicpu(hp1).opcode = A_ADD) or
  3972. (taicpu(hp1).opcode = A_SUB)) and
  3973. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  3974. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  3975. (((taicpu(hp1).opcode = A_INC) or
  3976. (taicpu(hp1).opcode = A_DEC)) and
  3977. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  3978. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  3979. ((taicpu(hp1).opcode = A_LEA) and
  3980. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3981. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  3982. (not GetNextInstruction(hp1,hp2) or
  3983. not instrReadsFlags(hp2)) Do
  3984. begin
  3985. TmpBool1 := False;
  3986. if taicpu(hp1).opcode=A_LEA then
  3987. begin
  3988. if (TmpRef.base = NR_NO) and
  3989. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  3990. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  3991. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  3992. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  3993. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  3994. begin
  3995. TmpBool1 := True;
  3996. TmpBool2 := True;
  3997. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  3998. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  3999. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  4000. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  4001. RemoveInstruction(hp1);
  4002. end
  4003. end
  4004. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  4005. begin
  4006. TmpBool1 := True;
  4007. TmpBool2 := True;
  4008. case taicpu(hp1).opcode of
  4009. A_ADD:
  4010. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4011. A_SUB:
  4012. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4013. else
  4014. internalerror(2019050536);
  4015. end;
  4016. RemoveInstruction(hp1);
  4017. end
  4018. else
  4019. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4020. (((taicpu(hp1).opcode = A_ADD) and
  4021. (TmpRef.base = NR_NO)) or
  4022. (taicpu(hp1).opcode = A_INC) or
  4023. (taicpu(hp1).opcode = A_DEC)) then
  4024. begin
  4025. TmpBool1 := True;
  4026. TmpBool2 := True;
  4027. case taicpu(hp1).opcode of
  4028. A_ADD:
  4029. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  4030. A_INC:
  4031. inc(TmpRef.offset);
  4032. A_DEC:
  4033. dec(TmpRef.offset);
  4034. else
  4035. internalerror(2019050535);
  4036. end;
  4037. RemoveInstruction(hp1);
  4038. end;
  4039. end;
  4040. if TmpBool2
  4041. {$ifndef x86_64}
  4042. or
  4043. ((current_settings.optimizecputype < cpu_Pentium2) and
  4044. (taicpu(p).oper[0]^.val <= 3) and
  4045. not(cs_opt_size in current_settings.optimizerswitches))
  4046. {$endif x86_64}
  4047. then
  4048. begin
  4049. if not(TmpBool2) and
  4050. (taicpu(p).oper[0]^.val=1) then
  4051. begin
  4052. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4053. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  4054. end
  4055. else
  4056. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  4057. taicpu(p).oper[1]^.reg);
  4058. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  4059. InsertLLItem(p.previous, p.next, hp1);
  4060. p.free;
  4061. p := hp1;
  4062. end;
  4063. end
  4064. {$ifndef x86_64}
  4065. else if (current_settings.optimizecputype < cpu_Pentium2) then
  4066. begin
  4067. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  4068. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  4069. (unlike shl, which is only Tairable in the U pipe) }
  4070. if taicpu(p).oper[0]^.val=1 then
  4071. begin
  4072. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4073. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  4074. InsertLLItem(p.previous, p.next, hp1);
  4075. p.free;
  4076. p := hp1;
  4077. end
  4078. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  4079. "shl $3, %reg" to "lea (,%reg,8), %reg }
  4080. else if (taicpu(p).opsize = S_L) and
  4081. (taicpu(p).oper[0]^.val<= 3) then
  4082. begin
  4083. reference_reset(tmpref,2,[]);
  4084. TmpRef.index := taicpu(p).oper[1]^.reg;
  4085. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4086. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  4087. InsertLLItem(p.previous, p.next, hp1);
  4088. p.free;
  4089. p := hp1;
  4090. end;
  4091. end
  4092. {$endif x86_64}
  4093. else if
  4094. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  4095. (
  4096. (
  4097. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  4098. SetAndTest(hp1, hp2)
  4099. {$ifdef x86_64}
  4100. ) or
  4101. (
  4102. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4103. GetNextInstruction(hp1, hp2) and
  4104. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  4105. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4106. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  4107. {$endif x86_64}
  4108. )
  4109. ) and
  4110. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  4111. begin
  4112. { Change:
  4113. shl x, %reg1
  4114. mov -(1<<x), %reg2
  4115. and %reg2, %reg1
  4116. Or:
  4117. shl x, %reg1
  4118. and -(1<<x), %reg1
  4119. To just:
  4120. shl x, %reg1
  4121. Since the and operation only zeroes bits that are already zero from the shl operation
  4122. }
  4123. case taicpu(p).oper[0]^.val of
  4124. 8:
  4125. mask:=$FFFFFFFFFFFFFF00;
  4126. 16:
  4127. mask:=$FFFFFFFFFFFF0000;
  4128. 32:
  4129. mask:=$FFFFFFFF00000000;
  4130. 63:
  4131. { Constant pre-calculated to prevent overflow errors with Int64 }
  4132. mask:=$8000000000000000;
  4133. else
  4134. begin
  4135. if taicpu(p).oper[0]^.val >= 64 then
  4136. { Shouldn't happen realistically, since the register
  4137. is guaranteed to be set to zero at this point }
  4138. mask := 0
  4139. else
  4140. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  4141. end;
  4142. end;
  4143. if taicpu(hp1).oper[0]^.val = mask then
  4144. begin
  4145. { Everything checks out, perform the optimisation, as long as
  4146. the FLAGS register isn't being used}
  4147. TransferUsedRegs(TmpUsedRegs);
  4148. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4149. {$ifdef x86_64}
  4150. if (hp1 <> hp2) then
  4151. begin
  4152. { "shl/mov/and" version }
  4153. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4154. { Don't do the optimisation if the FLAGS register is in use }
  4155. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  4156. begin
  4157. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  4158. { Don't remove the 'mov' instruction if its register is used elsewhere }
  4159. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  4160. begin
  4161. RemoveInstruction(hp1);
  4162. Result := True;
  4163. end;
  4164. { Only set Result to True if the 'mov' instruction was removed }
  4165. RemoveInstruction(hp2);
  4166. end;
  4167. end
  4168. else
  4169. {$endif x86_64}
  4170. begin
  4171. { "shl/and" version }
  4172. { Don't do the optimisation if the FLAGS register is in use }
  4173. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  4174. begin
  4175. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  4176. RemoveInstruction(hp1);
  4177. Result := True;
  4178. end;
  4179. end;
  4180. Exit;
  4181. end
  4182. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  4183. begin
  4184. { Even if the mask doesn't allow for its removal, we might be
  4185. able to optimise the mask for the "shl/and" version, which
  4186. may permit other peephole optimisations }
  4187. {$ifdef DEBUG_AOPTCPU}
  4188. mask := taicpu(hp1).oper[0]^.val and mask;
  4189. if taicpu(hp1).oper[0]^.val <> mask then
  4190. begin
  4191. DebugMsg(
  4192. SPeepholeOptimization +
  4193. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  4194. ' to $' + debug_tostr(mask) +
  4195. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  4196. taicpu(hp1).oper[0]^.val := mask;
  4197. end;
  4198. {$else DEBUG_AOPTCPU}
  4199. { If debugging is off, just set the operand even if it's the same }
  4200. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  4201. {$endif DEBUG_AOPTCPU}
  4202. end;
  4203. end;
  4204. end;
  4205. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  4206. var
  4207. CurrentRef: TReference;
  4208. FullReg: TRegister;
  4209. hp1, hp2: tai;
  4210. begin
  4211. Result := False;
  4212. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  4213. Exit;
  4214. { We assume you've checked if the operand is actually a reference by
  4215. this point. If it isn't, you'll most likely get an access violation }
  4216. CurrentRef := first_mov.oper[1]^.ref^;
  4217. { Memory must be aligned }
  4218. if (CurrentRef.offset mod 4) <> 0 then
  4219. Exit;
  4220. Inc(CurrentRef.offset);
  4221. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4222. if MatchOperand(second_mov.oper[0]^, 0) and
  4223. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  4224. GetNextInstruction(second_mov, hp1) and
  4225. (hp1.typ = ait_instruction) and
  4226. (taicpu(hp1).opcode = A_MOV) and
  4227. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4228. (taicpu(hp1).oper[0]^.val = 0) then
  4229. begin
  4230. Inc(CurrentRef.offset);
  4231. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  4232. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  4233. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  4234. begin
  4235. case taicpu(hp1).opsize of
  4236. S_B:
  4237. if GetNextInstruction(hp1, hp2) and
  4238. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  4239. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4240. (taicpu(hp2).oper[0]^.val = 0) then
  4241. begin
  4242. Inc(CurrentRef.offset);
  4243. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4244. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  4245. (taicpu(hp2).opsize = S_B) then
  4246. begin
  4247. RemoveInstruction(hp1);
  4248. RemoveInstruction(hp2);
  4249. first_mov.opsize := S_L;
  4250. if first_mov.oper[0]^.typ = top_reg then
  4251. begin
  4252. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  4253. { Reuse second_mov as a MOVZX instruction }
  4254. second_mov.opcode := A_MOVZX;
  4255. second_mov.opsize := S_BL;
  4256. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4257. second_mov.loadreg(1, FullReg);
  4258. first_mov.oper[0]^.reg := FullReg;
  4259. asml.Remove(second_mov);
  4260. asml.InsertBefore(second_mov, first_mov);
  4261. end
  4262. else
  4263. { It's a value }
  4264. begin
  4265. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  4266. RemoveInstruction(second_mov);
  4267. end;
  4268. Result := True;
  4269. Exit;
  4270. end;
  4271. end;
  4272. S_W:
  4273. begin
  4274. RemoveInstruction(hp1);
  4275. first_mov.opsize := S_L;
  4276. if first_mov.oper[0]^.typ = top_reg then
  4277. begin
  4278. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  4279. { Reuse second_mov as a MOVZX instruction }
  4280. second_mov.opcode := A_MOVZX;
  4281. second_mov.opsize := S_BL;
  4282. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4283. second_mov.loadreg(1, FullReg);
  4284. first_mov.oper[0]^.reg := FullReg;
  4285. asml.Remove(second_mov);
  4286. asml.InsertBefore(second_mov, first_mov);
  4287. end
  4288. else
  4289. { It's a value }
  4290. begin
  4291. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  4292. RemoveInstruction(second_mov);
  4293. end;
  4294. Result := True;
  4295. Exit;
  4296. end;
  4297. else
  4298. ;
  4299. end;
  4300. end;
  4301. end;
  4302. end;
  4303. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  4304. { returns true if a "continue" should be done after this optimization }
  4305. var
  4306. hp1, hp2: tai;
  4307. begin
  4308. Result := false;
  4309. if MatchOpType(taicpu(p),top_ref) and
  4310. GetNextInstruction(p, hp1) and
  4311. (hp1.typ = ait_instruction) and
  4312. (((taicpu(hp1).opcode = A_FLD) and
  4313. (taicpu(p).opcode = A_FSTP)) or
  4314. ((taicpu(p).opcode = A_FISTP) and
  4315. (taicpu(hp1).opcode = A_FILD))) and
  4316. MatchOpType(taicpu(hp1),top_ref) and
  4317. (taicpu(hp1).opsize = taicpu(p).opsize) and
  4318. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4319. begin
  4320. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  4321. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  4322. GetNextInstruction(hp1, hp2) and
  4323. (hp2.typ = ait_instruction) and
  4324. IsExitCode(hp2) and
  4325. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  4326. not(assigned(current_procinfo.procdef.funcretsym) and
  4327. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  4328. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  4329. begin
  4330. RemoveInstruction(hp1);
  4331. RemoveCurrentP(p, hp2);
  4332. RemoveLastDeallocForFuncRes(p);
  4333. Result := true;
  4334. end
  4335. else
  4336. { we can do this only in fast math mode as fstp is rounding ...
  4337. ... still disabled as it breaks the compiler and/or rtl }
  4338. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  4339. { ... or if another fstp equal to the first one follows }
  4340. (GetNextInstruction(hp1,hp2) and
  4341. (hp2.typ = ait_instruction) and
  4342. (taicpu(p).opcode=taicpu(hp2).opcode) and
  4343. (taicpu(p).opsize=taicpu(hp2).opsize))
  4344. ) and
  4345. { fst can't store an extended/comp value }
  4346. (taicpu(p).opsize <> S_FX) and
  4347. (taicpu(p).opsize <> S_IQ) then
  4348. begin
  4349. if (taicpu(p).opcode = A_FSTP) then
  4350. taicpu(p).opcode := A_FST
  4351. else
  4352. taicpu(p).opcode := A_FIST;
  4353. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  4354. RemoveInstruction(hp1);
  4355. end;
  4356. end;
  4357. end;
  4358. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  4359. var
  4360. hp1, hp2: tai;
  4361. begin
  4362. result:=false;
  4363. if MatchOpType(taicpu(p),top_reg) and
  4364. GetNextInstruction(p, hp1) and
  4365. (hp1.typ = Ait_Instruction) and
  4366. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4367. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  4368. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  4369. { change to
  4370. fld reg fxxx reg,st
  4371. fxxxp st, st1 (hp1)
  4372. Remark: non commutative operations must be reversed!
  4373. }
  4374. begin
  4375. case taicpu(hp1).opcode Of
  4376. A_FMULP,A_FADDP,
  4377. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4378. begin
  4379. case taicpu(hp1).opcode Of
  4380. A_FADDP: taicpu(hp1).opcode := A_FADD;
  4381. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  4382. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  4383. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  4384. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  4385. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  4386. else
  4387. internalerror(2019050534);
  4388. end;
  4389. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  4390. taicpu(hp1).oper[1]^.reg := NR_ST;
  4391. RemoveCurrentP(p, hp1);
  4392. Result:=true;
  4393. exit;
  4394. end;
  4395. else
  4396. ;
  4397. end;
  4398. end
  4399. else
  4400. if MatchOpType(taicpu(p),top_ref) and
  4401. GetNextInstruction(p, hp2) and
  4402. (hp2.typ = Ait_Instruction) and
  4403. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4404. (taicpu(p).opsize in [S_FS, S_FL]) and
  4405. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  4406. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  4407. if GetLastInstruction(p, hp1) and
  4408. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  4409. MatchOpType(taicpu(hp1),top_ref) and
  4410. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4411. if ((taicpu(hp2).opcode = A_FMULP) or
  4412. (taicpu(hp2).opcode = A_FADDP)) then
  4413. { change to
  4414. fld/fst mem1 (hp1) fld/fst mem1
  4415. fld mem1 (p) fadd/
  4416. faddp/ fmul st, st
  4417. fmulp st, st1 (hp2) }
  4418. begin
  4419. RemoveCurrentP(p, hp1);
  4420. if (taicpu(hp2).opcode = A_FADDP) then
  4421. taicpu(hp2).opcode := A_FADD
  4422. else
  4423. taicpu(hp2).opcode := A_FMUL;
  4424. taicpu(hp2).oper[1]^.reg := NR_ST;
  4425. end
  4426. else
  4427. { change to
  4428. fld/fst mem1 (hp1) fld/fst mem1
  4429. fld mem1 (p) fld st}
  4430. begin
  4431. taicpu(p).changeopsize(S_FL);
  4432. taicpu(p).loadreg(0,NR_ST);
  4433. end
  4434. else
  4435. begin
  4436. case taicpu(hp2).opcode Of
  4437. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4438. { change to
  4439. fld/fst mem1 (hp1) fld/fst mem1
  4440. fld mem2 (p) fxxx mem2
  4441. fxxxp st, st1 (hp2) }
  4442. begin
  4443. case taicpu(hp2).opcode Of
  4444. A_FADDP: taicpu(p).opcode := A_FADD;
  4445. A_FMULP: taicpu(p).opcode := A_FMUL;
  4446. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  4447. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  4448. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  4449. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  4450. else
  4451. internalerror(2019050533);
  4452. end;
  4453. RemoveInstruction(hp2);
  4454. end
  4455. else
  4456. ;
  4457. end
  4458. end
  4459. end;
  4460. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  4461. begin
  4462. Result := condition_in(cond1, cond2) or
  4463. { Not strictly subsets due to the actual flags checked, but because we're
  4464. comparing integers, E is a subset of AE and GE and their aliases }
  4465. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  4466. end;
  4467. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  4468. var
  4469. v: TCGInt;
  4470. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  4471. FirstMatch: Boolean;
  4472. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  4473. begin
  4474. Result:=false;
  4475. { All these optimisations need a next instruction }
  4476. if not GetNextInstruction(p, hp1) then
  4477. Exit;
  4478. { Search for:
  4479. cmp ###,###
  4480. j(c1) @lbl1
  4481. ...
  4482. @lbl:
  4483. cmp ###.### (same comparison as above)
  4484. j(c2) @lbl2
  4485. If c1 is a subset of c2, change to:
  4486. cmp ###,###
  4487. j(c2) @lbl2
  4488. (@lbl1 may become a dead label as a result)
  4489. }
  4490. { Also handle cases where there are multiple jumps in a row }
  4491. p_jump := hp1;
  4492. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  4493. begin
  4494. if IsJumpToLabel(taicpu(p_jump)) then
  4495. begin
  4496. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  4497. p_label := nil;
  4498. if Assigned(JumpLabel) then
  4499. p_label := getlabelwithsym(JumpLabel);
  4500. if Assigned(p_label) and
  4501. GetNextInstruction(p_label, p_dist) and
  4502. MatchInstruction(p_dist, A_CMP, []) and
  4503. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  4504. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4505. GetNextInstruction(p_dist, hp1_dist) and
  4506. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4507. begin
  4508. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4509. if JumpLabel = JumpLabel_dist then
  4510. { This is an infinite loop }
  4511. Exit;
  4512. { Best optimisation when the first condition is a subset (or equal) of the second }
  4513. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  4514. begin
  4515. { Any registers used here will already be allocated }
  4516. if Assigned(JumpLabel_dist) then
  4517. JumpLabel_dist.IncRefs;
  4518. if Assigned(JumpLabel) then
  4519. JumpLabel.DecRefs;
  4520. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  4521. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  4522. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4523. Result := True;
  4524. { Don't exit yet. Since p and p_jump haven't actually been
  4525. removed, we can check for more on this iteration }
  4526. end
  4527. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  4528. GetNextInstruction(hp1_dist, hp1_label) and
  4529. SkipAligns(hp1_label, hp1_label) and
  4530. (hp1_label.typ = ait_label) then
  4531. begin
  4532. JumpLabel_far := tai_label(hp1_label).labsym;
  4533. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  4534. { This is an infinite loop }
  4535. Exit;
  4536. if Assigned(JumpLabel_far) then
  4537. begin
  4538. { In this situation, if the first jump branches, the second one will never,
  4539. branch so change the destination label to after the second jump }
  4540. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  4541. if Assigned(JumpLabel) then
  4542. JumpLabel.DecRefs;
  4543. JumpLabel_far.IncRefs;
  4544. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  4545. Result := True;
  4546. { Don't exit yet. Since p and p_jump haven't actually been
  4547. removed, we can check for more on this iteration }
  4548. Continue;
  4549. end;
  4550. end;
  4551. end;
  4552. end;
  4553. { Search for:
  4554. cmp ###,###
  4555. j(c1) @lbl1
  4556. cmp ###,### (same as first)
  4557. Remove second cmp
  4558. }
  4559. if GetNextInstruction(p_jump, hp2) and
  4560. (
  4561. (
  4562. MatchInstruction(hp2, A_CMP, []) and
  4563. (
  4564. (
  4565. MatchOpType(taicpu(p), top_const, top_reg) and
  4566. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  4567. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  4568. ) or (
  4569. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  4570. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  4571. )
  4572. )
  4573. ) or (
  4574. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  4575. MatchOperand(taicpu(p).oper[0]^, 0) and
  4576. (taicpu(p).oper[1]^.typ = top_reg) and
  4577. MatchInstruction(hp2, A_TEST, []) and
  4578. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4579. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  4580. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  4581. )
  4582. ) then
  4583. begin
  4584. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  4585. RemoveInstruction(hp2);
  4586. Result := True;
  4587. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  4588. end;
  4589. GetNextInstruction(p_jump, p_jump);
  4590. end;
  4591. if taicpu(p).oper[0]^.typ = top_const then
  4592. begin
  4593. if (taicpu(p).oper[0]^.val = 0) and
  4594. (taicpu(p).oper[1]^.typ = top_reg) and
  4595. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  4596. begin
  4597. hp2 := p;
  4598. FirstMatch := True;
  4599. { When dealing with "cmp $0,%reg", only ZF and SF contain
  4600. anything meaningful once it's converted to "test %reg,%reg";
  4601. additionally, some jumps will always (or never) branch, so
  4602. evaluate every jump immediately following the
  4603. comparison, optimising the conditions if possible.
  4604. Similarly with SETcc... those that are always set to 0 or 1
  4605. are changed to MOV instructions }
  4606. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  4607. (
  4608. GetNextInstruction(hp2, hp1) and
  4609. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  4610. ) do
  4611. begin
  4612. FirstMatch := False;
  4613. case taicpu(hp1).condition of
  4614. C_B, C_C, C_NAE, C_O:
  4615. { For B/NAE:
  4616. Will never branch since an unsigned integer can never be below zero
  4617. For C/O:
  4618. Result cannot overflow because 0 is being subtracted
  4619. }
  4620. begin
  4621. if taicpu(hp1).opcode = A_Jcc then
  4622. begin
  4623. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  4624. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  4625. RemoveInstruction(hp1);
  4626. { Since hp1 was deleted, hp2 must not be updated }
  4627. Continue;
  4628. end
  4629. else
  4630. begin
  4631. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  4632. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  4633. taicpu(hp1).opcode := A_MOV;
  4634. taicpu(hp1).ops := 2;
  4635. taicpu(hp1).condition := C_None;
  4636. taicpu(hp1).opsize := S_B;
  4637. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4638. taicpu(hp1).loadconst(0, 0);
  4639. end;
  4640. end;
  4641. C_BE, C_NA:
  4642. begin
  4643. { Will only branch if equal to zero }
  4644. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  4645. taicpu(hp1).condition := C_E;
  4646. end;
  4647. C_A, C_NBE:
  4648. begin
  4649. { Will only branch if not equal to zero }
  4650. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  4651. taicpu(hp1).condition := C_NE;
  4652. end;
  4653. C_AE, C_NB, C_NC, C_NO:
  4654. begin
  4655. { Will always branch }
  4656. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  4657. if taicpu(hp1).opcode = A_Jcc then
  4658. begin
  4659. MakeUnconditional(taicpu(hp1));
  4660. { Any jumps/set that follow will now be dead code }
  4661. RemoveDeadCodeAfterJump(taicpu(hp1));
  4662. Break;
  4663. end
  4664. else
  4665. begin
  4666. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  4667. taicpu(hp1).opcode := A_MOV;
  4668. taicpu(hp1).ops := 2;
  4669. taicpu(hp1).condition := C_None;
  4670. taicpu(hp1).opsize := S_B;
  4671. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4672. taicpu(hp1).loadconst(0, 1);
  4673. end;
  4674. end;
  4675. C_None:
  4676. InternalError(2020012201);
  4677. C_P, C_PE, C_NP, C_PO:
  4678. { We can't handle parity checks and they should never be generated
  4679. after a general-purpose CMP (it's used in some floating-point
  4680. comparisons that don't use CMP) }
  4681. InternalError(2020012202);
  4682. else
  4683. { Zero/Equality, Sign, their complements and all of the
  4684. signed comparisons do not need to be converted };
  4685. end;
  4686. hp2 := hp1;
  4687. end;
  4688. { Convert the instruction to a TEST }
  4689. taicpu(p).opcode := A_TEST;
  4690. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  4691. Result := True;
  4692. Exit;
  4693. end
  4694. else if (taicpu(p).oper[0]^.val = 1) and
  4695. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  4696. (taicpu(hp1).condition in [C_L, C_NGE]) then
  4697. begin
  4698. { Convert; To:
  4699. cmp $1,r/m cmp $0,r/m
  4700. jl @lbl jle @lbl
  4701. }
  4702. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  4703. taicpu(p).oper[0]^.val := 0;
  4704. taicpu(hp1).condition := C_LE;
  4705. { If the instruction is now "cmp $0,%reg", convert it to a
  4706. TEST (and effectively do the work of the "cmp $0,%reg" in
  4707. the block above)
  4708. If it's a reference, we can get away with not setting
  4709. Result to True because he haven't evaluated the jump
  4710. in this pass yet.
  4711. }
  4712. if (taicpu(p).oper[1]^.typ = top_reg) then
  4713. begin
  4714. taicpu(p).opcode := A_TEST;
  4715. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  4716. Result := True;
  4717. end;
  4718. Exit;
  4719. end
  4720. else if (taicpu(p).oper[1]^.typ = top_reg) then
  4721. begin
  4722. { cmp register,$8000 neg register
  4723. je target --> jo target
  4724. .... only if register is deallocated before jump.}
  4725. case Taicpu(p).opsize of
  4726. S_B: v:=$80;
  4727. S_W: v:=$8000;
  4728. S_L: v:=qword($80000000);
  4729. { S_Q will never happen: cmp with 64 bit constants is not possible }
  4730. S_Q:
  4731. Exit;
  4732. else
  4733. internalerror(2013112905);
  4734. end;
  4735. if (taicpu(p).oper[0]^.val=v) and
  4736. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  4737. (Taicpu(hp1).condition in [C_E,C_NE]) then
  4738. begin
  4739. TransferUsedRegs(TmpUsedRegs);
  4740. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  4741. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  4742. begin
  4743. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  4744. Taicpu(p).opcode:=A_NEG;
  4745. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  4746. Taicpu(p).clearop(1);
  4747. Taicpu(p).ops:=1;
  4748. if Taicpu(hp1).condition=C_E then
  4749. Taicpu(hp1).condition:=C_O
  4750. else
  4751. Taicpu(hp1).condition:=C_NO;
  4752. Result:=true;
  4753. exit;
  4754. end;
  4755. end;
  4756. end;
  4757. end;
  4758. if (taicpu(p).oper[1]^.typ = top_reg) and
  4759. MatchInstruction(hp1,A_MOV,[]) and
  4760. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  4761. (
  4762. (taicpu(p).oper[0]^.typ <> top_reg) or
  4763. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  4764. ) then
  4765. begin
  4766. { If we have something like:
  4767. cmp ###,%reg1
  4768. mov 0,%reg2
  4769. And no registers are shared, move the MOV command to before the
  4770. comparison as this means it can be optimised without worrying
  4771. about the FLAGS register. (This combination is generated by
  4772. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  4773. }
  4774. SwapMovCmp(p, hp1);
  4775. Result := True;
  4776. Exit;
  4777. end;
  4778. end;
  4779. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  4780. var
  4781. hp1: tai;
  4782. begin
  4783. {
  4784. remove the second (v)pxor from
  4785. pxor reg,reg
  4786. ...
  4787. pxor reg,reg
  4788. }
  4789. Result:=false;
  4790. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  4791. MatchOpType(taicpu(p),top_reg,top_reg) and
  4792. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4793. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4794. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4795. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  4796. begin
  4797. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  4798. RemoveInstruction(hp1);
  4799. Result:=true;
  4800. Exit;
  4801. end
  4802. {
  4803. replace
  4804. pxor reg1,reg1
  4805. movapd/s reg1,reg2
  4806. dealloc reg1
  4807. by
  4808. pxor reg2,reg2
  4809. }
  4810. else if GetNextInstruction(p,hp1) and
  4811. { we mix single and double opperations here because we assume that the compiler
  4812. generates vmovapd only after double operations and vmovaps only after single operations }
  4813. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4814. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  4815. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4816. (taicpu(p).oper[0]^.typ=top_reg) then
  4817. begin
  4818. TransferUsedRegs(TmpUsedRegs);
  4819. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4820. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4821. begin
  4822. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  4823. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4824. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  4825. RemoveInstruction(hp1);
  4826. result:=true;
  4827. end;
  4828. end;
  4829. end;
  4830. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  4831. var
  4832. hp1: tai;
  4833. begin
  4834. {
  4835. remove the second (v)pxor from
  4836. (v)pxor reg,reg
  4837. ...
  4838. (v)pxor reg,reg
  4839. }
  4840. Result:=false;
  4841. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  4842. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  4843. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4844. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4845. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4846. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  4847. begin
  4848. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  4849. RemoveInstruction(hp1);
  4850. Result:=true;
  4851. Exit;
  4852. end
  4853. else
  4854. Result:=OptPass1VOP(p);
  4855. end;
  4856. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  4857. var
  4858. hp1 : tai;
  4859. begin
  4860. result:=false;
  4861. { replace
  4862. IMul const,%mreg1,%mreg2
  4863. Mov %reg2,%mreg3
  4864. dealloc %mreg3
  4865. by
  4866. Imul const,%mreg1,%mreg23
  4867. }
  4868. if (taicpu(p).ops=3) and
  4869. GetNextInstruction(p,hp1) and
  4870. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4871. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  4872. (taicpu(hp1).oper[1]^.typ=top_reg) then
  4873. begin
  4874. TransferUsedRegs(TmpUsedRegs);
  4875. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4876. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  4877. begin
  4878. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  4879. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  4880. RemoveInstruction(hp1);
  4881. result:=true;
  4882. end;
  4883. end;
  4884. end;
  4885. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  4886. var
  4887. hp1 : tai;
  4888. begin
  4889. result:=false;
  4890. { replace
  4891. IMul %reg0,%reg1,%reg2
  4892. Mov %reg2,%reg3
  4893. dealloc %reg2
  4894. by
  4895. Imul %reg0,%reg1,%reg3
  4896. }
  4897. if GetNextInstruction(p,hp1) and
  4898. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4899. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  4900. (taicpu(hp1).oper[1]^.typ=top_reg) then
  4901. begin
  4902. TransferUsedRegs(TmpUsedRegs);
  4903. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4904. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  4905. begin
  4906. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  4907. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  4908. RemoveInstruction(hp1);
  4909. result:=true;
  4910. end;
  4911. end;
  4912. end;
  4913. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  4914. var
  4915. hp1, hp2, hp3, hp4, hp5: tai;
  4916. ThisReg: TRegister;
  4917. begin
  4918. Result := False;
  4919. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  4920. Exit;
  4921. {
  4922. convert
  4923. j<c> .L1
  4924. mov 1,reg
  4925. jmp .L2
  4926. .L1
  4927. mov 0,reg
  4928. .L2
  4929. into
  4930. mov 0,reg
  4931. set<not(c)> reg
  4932. take care of alignment and that the mov 0,reg is not converted into a xor as this
  4933. would destroy the flag contents
  4934. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  4935. executed at the same time as a previous comparison.
  4936. set<not(c)> reg
  4937. movzx reg, reg
  4938. }
  4939. if MatchInstruction(hp1,A_MOV,[]) and
  4940. (taicpu(hp1).oper[0]^.typ = top_const) and
  4941. (
  4942. (
  4943. (taicpu(hp1).oper[1]^.typ = top_reg)
  4944. {$ifdef i386}
  4945. { Under i386, ESI, EDI, EBP and ESP
  4946. don't have an 8-bit representation }
  4947. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  4948. {$endif i386}
  4949. ) or (
  4950. {$ifdef i386}
  4951. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  4952. {$endif i386}
  4953. (taicpu(hp1).opsize = S_B)
  4954. )
  4955. ) and
  4956. GetNextInstruction(hp1,hp2) and
  4957. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  4958. GetNextInstruction(hp2,hp3) and
  4959. SkipAligns(hp3, hp3) and
  4960. (hp3.typ=ait_label) and
  4961. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  4962. GetNextInstruction(hp3,hp4) and
  4963. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  4964. (taicpu(hp4).oper[0]^.typ = top_const) and
  4965. (
  4966. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  4967. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  4968. ) and
  4969. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  4970. GetNextInstruction(hp4,hp5) and
  4971. SkipAligns(hp5, hp5) and
  4972. (hp5.typ=ait_label) and
  4973. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  4974. begin
  4975. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  4976. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  4977. tai_label(hp3).labsym.DecRefs;
  4978. { If this isn't the only reference to the middle label, we can
  4979. still make a saving - only that the first jump and everything
  4980. that follows will remain. }
  4981. if (tai_label(hp3).labsym.getrefs = 0) then
  4982. begin
  4983. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  4984. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  4985. else
  4986. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  4987. { remove jump, first label and second MOV (also catching any aligns) }
  4988. repeat
  4989. if not GetNextInstruction(hp2, hp3) then
  4990. InternalError(2021040810);
  4991. RemoveInstruction(hp2);
  4992. hp2 := hp3;
  4993. until hp2 = hp5;
  4994. { Don't decrement reference count before the removal loop
  4995. above, otherwise GetNextInstruction won't stop on the
  4996. the label }
  4997. tai_label(hp5).labsym.DecRefs;
  4998. end
  4999. else
  5000. begin
  5001. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5002. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  5003. else
  5004. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  5005. end;
  5006. taicpu(p).opcode:=A_SETcc;
  5007. taicpu(p).opsize:=S_B;
  5008. taicpu(p).is_jmp:=False;
  5009. if taicpu(hp1).opsize=S_B then
  5010. begin
  5011. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  5012. RemoveInstruction(hp1);
  5013. end
  5014. else
  5015. begin
  5016. { Will be a register because the size can't be S_B otherwise }
  5017. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  5018. taicpu(p).loadreg(0, ThisReg);
  5019. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  5020. begin
  5021. case taicpu(hp1).opsize of
  5022. S_W:
  5023. taicpu(hp1).opsize := S_BW;
  5024. S_L:
  5025. taicpu(hp1).opsize := S_BL;
  5026. {$ifdef x86_64}
  5027. S_Q:
  5028. begin
  5029. taicpu(hp1).opsize := S_BL;
  5030. { Change the destination register to 32-bit }
  5031. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  5032. end;
  5033. {$endif x86_64}
  5034. else
  5035. InternalError(2021040820);
  5036. end;
  5037. taicpu(hp1).opcode := A_MOVZX;
  5038. taicpu(hp1).loadreg(0, ThisReg);
  5039. end
  5040. else
  5041. begin
  5042. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  5043. { hp1 is already a MOV instruction with the correct register }
  5044. taicpu(hp1).loadconst(0, 0);
  5045. { Inserting it right before p will guarantee that the flags are also tracked }
  5046. asml.Remove(hp1);
  5047. asml.InsertBefore(hp1, p);
  5048. end;
  5049. end;
  5050. Result:=true;
  5051. exit;
  5052. end
  5053. end;
  5054. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  5055. var
  5056. hp2, hp3, first_assignment: tai;
  5057. IncCount, OperIdx: Integer;
  5058. OrigLabel: TAsmLabel;
  5059. begin
  5060. Count := 0;
  5061. Result := False;
  5062. first_assignment := nil;
  5063. if (LoopCount >= 20) then
  5064. begin
  5065. { Guard against infinite loops }
  5066. Exit;
  5067. end;
  5068. if (taicpu(p).oper[0]^.typ <> top_ref) or
  5069. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  5070. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  5071. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  5072. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  5073. Exit;
  5074. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  5075. {
  5076. change
  5077. jmp .L1
  5078. ...
  5079. .L1:
  5080. mov ##, ## ( multiple movs possible )
  5081. jmp/ret
  5082. into
  5083. mov ##, ##
  5084. jmp/ret
  5085. }
  5086. if not Assigned(hp1) then
  5087. begin
  5088. hp1 := GetLabelWithSym(OrigLabel);
  5089. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  5090. Exit;
  5091. end;
  5092. hp2 := hp1;
  5093. while Assigned(hp2) do
  5094. begin
  5095. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  5096. SkipLabels(hp2,hp2);
  5097. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  5098. Break;
  5099. case taicpu(hp2).opcode of
  5100. A_MOVSS:
  5101. begin
  5102. if taicpu(hp2).ops = 0 then
  5103. { Wrong MOVSS }
  5104. Break;
  5105. Inc(Count);
  5106. if Count >= 5 then
  5107. { Too many to be worthwhile }
  5108. Break;
  5109. GetNextInstruction(hp2, hp2);
  5110. Continue;
  5111. end;
  5112. A_MOV,
  5113. A_MOVD,
  5114. A_MOVQ,
  5115. A_MOVSX,
  5116. {$ifdef x86_64}
  5117. A_MOVSXD,
  5118. {$endif x86_64}
  5119. A_MOVZX,
  5120. A_MOVAPS,
  5121. A_MOVUPS,
  5122. A_MOVSD,
  5123. A_MOVAPD,
  5124. A_MOVUPD,
  5125. A_MOVDQA,
  5126. A_MOVDQU,
  5127. A_VMOVSS,
  5128. A_VMOVAPS,
  5129. A_VMOVUPS,
  5130. A_VMOVSD,
  5131. A_VMOVAPD,
  5132. A_VMOVUPD,
  5133. A_VMOVDQA,
  5134. A_VMOVDQU:
  5135. begin
  5136. Inc(Count);
  5137. if Count >= 5 then
  5138. { Too many to be worthwhile }
  5139. Break;
  5140. GetNextInstruction(hp2, hp2);
  5141. Continue;
  5142. end;
  5143. A_JMP:
  5144. begin
  5145. { Guard against infinite loops }
  5146. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  5147. Exit;
  5148. { Analyse this jump first in case it also duplicates assignments }
  5149. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  5150. begin
  5151. { Something did change! }
  5152. Result := True;
  5153. Inc(Count, IncCount);
  5154. if Count >= 5 then
  5155. begin
  5156. { Too many to be worthwhile }
  5157. Exit;
  5158. end;
  5159. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  5160. Break;
  5161. end;
  5162. Result := True;
  5163. Break;
  5164. end;
  5165. A_RET:
  5166. begin
  5167. Result := True;
  5168. Break;
  5169. end;
  5170. else
  5171. Break;
  5172. end;
  5173. end;
  5174. if Result then
  5175. begin
  5176. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  5177. if Count = 0 then
  5178. begin
  5179. Result := False;
  5180. Exit;
  5181. end;
  5182. hp3 := p;
  5183. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  5184. while True do
  5185. begin
  5186. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  5187. SkipLabels(hp1,hp1);
  5188. if (hp1.typ <> ait_instruction) then
  5189. InternalError(2021040720);
  5190. case taicpu(hp1).opcode of
  5191. A_JMP:
  5192. begin
  5193. { Change the original jump to the new destination }
  5194. OrigLabel.decrefs;
  5195. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  5196. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  5197. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5198. if not Assigned(first_assignment) then
  5199. InternalError(2021040810)
  5200. else
  5201. p := first_assignment;
  5202. Exit;
  5203. end;
  5204. A_RET:
  5205. begin
  5206. { Now change the jump into a RET instruction }
  5207. ConvertJumpToRET(p, hp1);
  5208. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5209. if not Assigned(first_assignment) then
  5210. InternalError(2021040811)
  5211. else
  5212. p := first_assignment;
  5213. Exit;
  5214. end;
  5215. else
  5216. begin
  5217. { Duplicate the MOV instruction }
  5218. hp3:=tai(hp1.getcopy);
  5219. if first_assignment = nil then
  5220. first_assignment := hp3;
  5221. asml.InsertBefore(hp3, p);
  5222. { Make sure the compiler knows about any final registers written here }
  5223. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  5224. with taicpu(hp3).oper[OperIdx]^ do
  5225. begin
  5226. case typ of
  5227. top_ref:
  5228. begin
  5229. if (ref^.base <> NR_NO) and
  5230. (getsupreg(ref^.base) <> RS_ESP) and
  5231. (getsupreg(ref^.base) <> RS_EBP)
  5232. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  5233. then
  5234. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  5235. if (ref^.index <> NR_NO) and
  5236. (getsupreg(ref^.index) <> RS_ESP) and
  5237. (getsupreg(ref^.index) <> RS_EBP)
  5238. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  5239. (ref^.index <> ref^.base) then
  5240. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  5241. end;
  5242. top_reg:
  5243. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  5244. else
  5245. ;
  5246. end;
  5247. end;
  5248. end;
  5249. end;
  5250. if not GetNextInstruction(hp1, hp1) then
  5251. { Should have dropped out earlier }
  5252. InternalError(2021040710);
  5253. end;
  5254. end;
  5255. end;
  5256. procedure TX86AsmOptimizer.SwapMovCmp(var p, hp1: tai);
  5257. var
  5258. hp2: tai;
  5259. X: Integer;
  5260. begin
  5261. asml.Remove(hp1);
  5262. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  5263. if not GetLastInstruction(p, hp2) then
  5264. asml.InsertBefore(hp1, p)
  5265. else
  5266. asml.InsertAfter(hp1, hp2);
  5267. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and mov instructions to improve optimisation potential', hp1);
  5268. for X := 0 to 1 do
  5269. case taicpu(hp1).oper[X]^.typ of
  5270. top_reg:
  5271. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  5272. top_ref:
  5273. begin
  5274. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  5275. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  5276. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  5277. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  5278. end;
  5279. else
  5280. ;
  5281. end;
  5282. end;
  5283. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  5284. function IsXCHGAcceptable: Boolean; inline;
  5285. begin
  5286. { Always accept if optimising for size }
  5287. Result := (cs_opt_size in current_settings.optimizerswitches) or
  5288. (
  5289. {$ifdef x86_64}
  5290. { XCHG takes 3 cycles on AMD Athlon64 }
  5291. (current_settings.optimizecputype >= cpu_core_i)
  5292. {$else x86_64}
  5293. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  5294. than 3, so it becomes a saving compared to three MOVs with two of
  5295. them able to execute simultaneously. [Kit] }
  5296. (current_settings.optimizecputype >= cpu_PentiumM)
  5297. {$endif x86_64}
  5298. );
  5299. end;
  5300. var
  5301. NewRef: TReference;
  5302. hp1, hp2, hp3, hp4: Tai;
  5303. {$ifndef x86_64}
  5304. OperIdx: Integer;
  5305. {$endif x86_64}
  5306. NewInstr : Taicpu;
  5307. NewAligh : Tai_align;
  5308. DestLabel: TAsmLabel;
  5309. begin
  5310. Result:=false;
  5311. { This optimisation adds an instruction, so only do it for speed }
  5312. if not (cs_opt_size in current_settings.optimizerswitches) and
  5313. MatchOpType(taicpu(p), top_const, top_reg) and
  5314. (taicpu(p).oper[0]^.val = 0) then
  5315. begin
  5316. { To avoid compiler warning }
  5317. DestLabel := nil;
  5318. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  5319. InternalError(2021040750);
  5320. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  5321. Exit;
  5322. case hp1.typ of
  5323. ait_label:
  5324. begin
  5325. { Change:
  5326. mov $0,%reg mov $0,%reg
  5327. @Lbl1: @Lbl1:
  5328. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  5329. je @Lbl2 jne @Lbl2
  5330. To: To:
  5331. mov $0,%reg mov $0,%reg
  5332. jmp @Lbl2 jmp @Lbl3
  5333. (align) (align)
  5334. @Lbl1: @Lbl1:
  5335. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  5336. je @Lbl2 je @Lbl2
  5337. @Lbl3: <-- Only if label exists
  5338. (Not if it's optimised for size)
  5339. }
  5340. if not GetNextInstruction(hp1, hp2) then
  5341. Exit;
  5342. if not (cs_opt_size in current_settings.optimizerswitches) and
  5343. (hp2.typ = ait_instruction) and
  5344. (
  5345. { Register sizes must exactly match }
  5346. (
  5347. (taicpu(hp2).opcode = A_CMP) and
  5348. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  5349. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5350. ) or (
  5351. (taicpu(hp2).opcode = A_TEST) and
  5352. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5353. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5354. )
  5355. ) and GetNextInstruction(hp2, hp3) and
  5356. (hp3.typ = ait_instruction) and
  5357. (taicpu(hp3).opcode = A_JCC) and
  5358. (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
  5359. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  5360. begin
  5361. { Check condition of jump }
  5362. { Always true? }
  5363. if condition_in(C_E, taicpu(hp3).condition) then
  5364. begin
  5365. { Copy label symbol and obtain matching label entry for the
  5366. conditional jump, as this will be our destination}
  5367. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  5368. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  5369. Result := True;
  5370. end
  5371. { Always false? }
  5372. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  5373. begin
  5374. { This is only worth it if there's a jump to take }
  5375. case hp2.typ of
  5376. ait_instruction:
  5377. begin
  5378. if taicpu(hp2).opcode = A_JMP then
  5379. begin
  5380. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5381. { An unconditional jump follows the conditional jump which will always be false,
  5382. so use this jump's destination for the new jump }
  5383. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  5384. Result := True;
  5385. end
  5386. else if taicpu(hp2).opcode = A_JCC then
  5387. begin
  5388. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5389. if condition_in(C_E, taicpu(hp2).condition) then
  5390. begin
  5391. { A second conditional jump follows the conditional jump which will always be false,
  5392. while the second jump is always True, so use this jump's destination for the new jump }
  5393. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  5394. Result := True;
  5395. end;
  5396. { Don't risk it if the jump isn't always true (Result remains False) }
  5397. end;
  5398. end;
  5399. else
  5400. { If anything else don't optimise };
  5401. end;
  5402. end;
  5403. if Result then
  5404. begin
  5405. { Just so we have something to insert as a paremeter}
  5406. reference_reset(NewRef, 1, []);
  5407. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  5408. { Now actually load the correct parameter }
  5409. NewInstr.loadsymbol(0, DestLabel, 0);
  5410. { Get instruction before original label (may not be p under -O3) }
  5411. if not GetLastInstruction(hp1, hp2) then
  5412. { Shouldn't fail here }
  5413. InternalError(2021040701);
  5414. DestLabel.increfs;
  5415. AsmL.InsertAfter(NewInstr, hp2);
  5416. { Add new alignment field }
  5417. (* AsmL.InsertAfter(
  5418. cai_align.create_max(
  5419. current_settings.alignment.jumpalign,
  5420. current_settings.alignment.jumpalignskipmax
  5421. ),
  5422. NewInstr
  5423. ); *)
  5424. end;
  5425. Exit;
  5426. end;
  5427. end;
  5428. else
  5429. ;
  5430. end;
  5431. end;
  5432. if not GetNextInstruction(p, hp1) then
  5433. Exit;
  5434. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  5435. begin
  5436. { Sometimes the MOVs that OptPass2JMP produces can be improved
  5437. further, but we can't just put this jump optimisation in pass 1
  5438. because it tends to perform worse when conditional jumps are
  5439. nearby (e.g. when converting CMOV instructions). [Kit] }
  5440. if OptPass2JMP(hp1) then
  5441. { call OptPass1MOV once to potentially merge any MOVs that were created }
  5442. Result := OptPass1MOV(p)
  5443. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  5444. returned True and the instruction is still a MOV, thus checking
  5445. the optimisations below }
  5446. { If OptPass2JMP returned False, no optimisations were done to
  5447. the jump and there are no further optimisations that can be done
  5448. to the MOV instruction on this pass }
  5449. end
  5450. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5451. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  5452. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5453. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5454. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5455. { be lazy, checking separately for sub would be slightly better }
  5456. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  5457. begin
  5458. { Change:
  5459. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  5460. addl/q $x,%reg2 subl/q $x,%reg2
  5461. To:
  5462. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  5463. }
  5464. TransferUsedRegs(TmpUsedRegs);
  5465. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5466. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5467. if not GetNextInstruction(hp1, hp2) or
  5468. (
  5469. { The FLAGS register isn't always tracked properly, so do not
  5470. perform this optimisation if a conditional statement follows }
  5471. not RegReadByInstruction(NR_DEFAULTFLAGS, hp2) and
  5472. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)
  5473. ) then
  5474. begin
  5475. reference_reset(NewRef, 1, []);
  5476. NewRef.base := taicpu(p).oper[0]^.reg;
  5477. NewRef.scalefactor := 1;
  5478. if taicpu(hp1).opcode = A_ADD then
  5479. begin
  5480. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  5481. NewRef.offset := taicpu(hp1).oper[0]^.val;
  5482. end
  5483. else
  5484. begin
  5485. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  5486. NewRef.offset := -taicpu(hp1).oper[0]^.val;
  5487. end;
  5488. taicpu(p).opcode := A_LEA;
  5489. taicpu(p).loadref(0, NewRef);
  5490. RemoveInstruction(hp1);
  5491. Result := True;
  5492. Exit;
  5493. end;
  5494. end
  5495. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5496. {$ifdef x86_64}
  5497. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  5498. {$else x86_64}
  5499. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  5500. {$endif x86_64}
  5501. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5502. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  5503. { mov reg1, reg2 mov reg1, reg2
  5504. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  5505. begin
  5506. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5507. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  5508. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  5509. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  5510. TransferUsedRegs(TmpUsedRegs);
  5511. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5512. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  5513. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  5514. then
  5515. begin
  5516. RemoveCurrentP(p, hp1);
  5517. Result:=true;
  5518. end;
  5519. exit;
  5520. end
  5521. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5522. IsXCHGAcceptable and
  5523. { XCHG doesn't support 8-byte registers }
  5524. (taicpu(p).opsize <> S_B) and
  5525. MatchInstruction(hp1, A_MOV, []) and
  5526. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5527. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  5528. GetNextInstruction(hp1, hp2) and
  5529. MatchInstruction(hp2, A_MOV, []) and
  5530. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  5531. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5532. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  5533. begin
  5534. { mov %reg1,%reg2
  5535. mov %reg3,%reg1 -> xchg %reg3,%reg1
  5536. mov %reg2,%reg3
  5537. (%reg2 not used afterwards)
  5538. Note that xchg takes 3 cycles to execute, and generally mov's take
  5539. only one cycle apiece, but the first two mov's can be executed in
  5540. parallel, only taking 2 cycles overall. Older processors should
  5541. therefore only optimise for size. [Kit]
  5542. }
  5543. TransferUsedRegs(TmpUsedRegs);
  5544. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5545. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5546. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  5547. begin
  5548. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  5549. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  5550. taicpu(hp1).opcode := A_XCHG;
  5551. RemoveCurrentP(p, hp1);
  5552. RemoveInstruction(hp2);
  5553. Result := True;
  5554. Exit;
  5555. end;
  5556. end
  5557. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5558. MatchInstruction(hp1, A_SAR, []) then
  5559. begin
  5560. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  5561. begin
  5562. { the use of %edx also covers the opsize being S_L }
  5563. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  5564. begin
  5565. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  5566. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  5567. (taicpu(p).oper[1]^.reg = NR_EDX) then
  5568. begin
  5569. { Change:
  5570. movl %eax,%edx
  5571. sarl $31,%edx
  5572. To:
  5573. cltd
  5574. }
  5575. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  5576. RemoveInstruction(hp1);
  5577. taicpu(p).opcode := A_CDQ;
  5578. taicpu(p).opsize := S_NO;
  5579. taicpu(p).clearop(1);
  5580. taicpu(p).clearop(0);
  5581. taicpu(p).ops:=0;
  5582. Result := True;
  5583. end
  5584. else if (cs_opt_size in current_settings.optimizerswitches) and
  5585. (taicpu(p).oper[0]^.reg = NR_EDX) and
  5586. (taicpu(p).oper[1]^.reg = NR_EAX) then
  5587. begin
  5588. { Change:
  5589. movl %edx,%eax
  5590. sarl $31,%edx
  5591. To:
  5592. movl %edx,%eax
  5593. cltd
  5594. Note that this creates a dependency between the two instructions,
  5595. so only perform if optimising for size.
  5596. }
  5597. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  5598. taicpu(hp1).opcode := A_CDQ;
  5599. taicpu(hp1).opsize := S_NO;
  5600. taicpu(hp1).clearop(1);
  5601. taicpu(hp1).clearop(0);
  5602. taicpu(hp1).ops:=0;
  5603. end;
  5604. {$ifndef x86_64}
  5605. end
  5606. { Don't bother if CMOV is supported, because a more optimal
  5607. sequence would have been generated for the Abs() intrinsic }
  5608. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  5609. { the use of %eax also covers the opsize being S_L }
  5610. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  5611. (taicpu(p).oper[0]^.reg = NR_EAX) and
  5612. (taicpu(p).oper[1]^.reg = NR_EDX) and
  5613. GetNextInstruction(hp1, hp2) and
  5614. MatchInstruction(hp2, A_XOR, [S_L]) and
  5615. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  5616. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  5617. GetNextInstruction(hp2, hp3) and
  5618. MatchInstruction(hp3, A_SUB, [S_L]) and
  5619. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  5620. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  5621. begin
  5622. { Change:
  5623. movl %eax,%edx
  5624. sarl $31,%eax
  5625. xorl %eax,%edx
  5626. subl %eax,%edx
  5627. (Instruction that uses %edx)
  5628. (%eax deallocated)
  5629. (%edx deallocated)
  5630. To:
  5631. cltd
  5632. xorl %edx,%eax <-- Note the registers have swapped
  5633. subl %edx,%eax
  5634. (Instruction that uses %eax) <-- %eax rather than %edx
  5635. }
  5636. TransferUsedRegs(TmpUsedRegs);
  5637. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5638. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5639. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5640. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  5641. begin
  5642. if GetNextInstruction(hp3, hp4) and
  5643. not RegModifiedByInstruction(NR_EDX, hp4) and
  5644. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  5645. begin
  5646. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  5647. taicpu(p).opcode := A_CDQ;
  5648. taicpu(p).clearop(1);
  5649. taicpu(p).clearop(0);
  5650. taicpu(p).ops:=0;
  5651. RemoveInstruction(hp1);
  5652. taicpu(hp2).loadreg(0, NR_EDX);
  5653. taicpu(hp2).loadreg(1, NR_EAX);
  5654. taicpu(hp3).loadreg(0, NR_EDX);
  5655. taicpu(hp3).loadreg(1, NR_EAX);
  5656. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  5657. { Convert references in the following instruction (hp4) from %edx to %eax }
  5658. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  5659. with taicpu(hp4).oper[OperIdx]^ do
  5660. case typ of
  5661. top_reg:
  5662. if getsupreg(reg) = RS_EDX then
  5663. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5664. top_ref:
  5665. begin
  5666. if getsupreg(reg) = RS_EDX then
  5667. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5668. if getsupreg(reg) = RS_EDX then
  5669. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5670. end;
  5671. else
  5672. ;
  5673. end;
  5674. end;
  5675. end;
  5676. {$else x86_64}
  5677. end;
  5678. end
  5679. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  5680. { the use of %rdx also covers the opsize being S_Q }
  5681. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  5682. begin
  5683. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  5684. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  5685. (taicpu(p).oper[1]^.reg = NR_RDX) then
  5686. begin
  5687. { Change:
  5688. movq %rax,%rdx
  5689. sarq $63,%rdx
  5690. To:
  5691. cqto
  5692. }
  5693. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  5694. RemoveInstruction(hp1);
  5695. taicpu(p).opcode := A_CQO;
  5696. taicpu(p).opsize := S_NO;
  5697. taicpu(p).clearop(1);
  5698. taicpu(p).clearop(0);
  5699. taicpu(p).ops:=0;
  5700. Result := True;
  5701. end
  5702. else if (cs_opt_size in current_settings.optimizerswitches) and
  5703. (taicpu(p).oper[0]^.reg = NR_RDX) and
  5704. (taicpu(p).oper[1]^.reg = NR_RAX) then
  5705. begin
  5706. { Change:
  5707. movq %rdx,%rax
  5708. sarq $63,%rdx
  5709. To:
  5710. movq %rdx,%rax
  5711. cqto
  5712. Note that this creates a dependency between the two instructions,
  5713. so only perform if optimising for size.
  5714. }
  5715. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  5716. taicpu(hp1).opcode := A_CQO;
  5717. taicpu(hp1).opsize := S_NO;
  5718. taicpu(hp1).clearop(1);
  5719. taicpu(hp1).clearop(0);
  5720. taicpu(hp1).ops:=0;
  5721. {$endif x86_64}
  5722. end;
  5723. end;
  5724. end
  5725. else if MatchInstruction(hp1, A_MOV, []) and
  5726. (taicpu(hp1).oper[1]^.typ = top_reg) then
  5727. { Though "GetNextInstruction" could be factored out, along with
  5728. the instructions that depend on hp2, it is an expensive call that
  5729. should be delayed for as long as possible, hence we do cheaper
  5730. checks first that are likely to be False. [Kit] }
  5731. begin
  5732. if (
  5733. (
  5734. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  5735. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  5736. (
  5737. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5738. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  5739. )
  5740. ) or
  5741. (
  5742. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  5743. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  5744. (
  5745. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5746. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  5747. )
  5748. )
  5749. ) and
  5750. GetNextInstruction(hp1, hp2) and
  5751. MatchInstruction(hp2, A_SAR, []) and
  5752. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  5753. begin
  5754. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  5755. begin
  5756. { Change:
  5757. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  5758. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  5759. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  5760. To:
  5761. movl r/m,%eax <- Note the change in register
  5762. cltd
  5763. }
  5764. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  5765. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  5766. taicpu(p).loadreg(1, NR_EAX);
  5767. taicpu(hp1).opcode := A_CDQ;
  5768. taicpu(hp1).clearop(1);
  5769. taicpu(hp1).clearop(0);
  5770. taicpu(hp1).ops:=0;
  5771. RemoveInstruction(hp2);
  5772. (*
  5773. {$ifdef x86_64}
  5774. end
  5775. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  5776. { This code sequence does not get generated - however it might become useful
  5777. if and when 128-bit signed integer types make an appearance, so the code
  5778. is kept here for when it is eventually needed. [Kit] }
  5779. (
  5780. (
  5781. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  5782. (
  5783. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5784. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  5785. )
  5786. ) or
  5787. (
  5788. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  5789. (
  5790. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5791. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  5792. )
  5793. )
  5794. ) and
  5795. GetNextInstruction(hp1, hp2) and
  5796. MatchInstruction(hp2, A_SAR, [S_Q]) and
  5797. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  5798. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  5799. begin
  5800. { Change:
  5801. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  5802. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  5803. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  5804. To:
  5805. movq r/m,%rax <- Note the change in register
  5806. cqto
  5807. }
  5808. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  5809. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  5810. taicpu(p).loadreg(1, NR_RAX);
  5811. taicpu(hp1).opcode := A_CQO;
  5812. taicpu(hp1).clearop(1);
  5813. taicpu(hp1).clearop(0);
  5814. taicpu(hp1).ops:=0;
  5815. RemoveInstruction(hp2);
  5816. {$endif x86_64}
  5817. *)
  5818. end;
  5819. end;
  5820. {$ifdef x86_64}
  5821. end
  5822. else if (taicpu(p).opsize = S_L) and
  5823. (taicpu(p).oper[1]^.typ = top_reg) and
  5824. (
  5825. MatchInstruction(hp1, A_MOV,[]) and
  5826. (taicpu(hp1).opsize = S_L) and
  5827. (taicpu(hp1).oper[1]^.typ = top_reg)
  5828. ) and (
  5829. GetNextInstruction(hp1, hp2) and
  5830. (tai(hp2).typ=ait_instruction) and
  5831. (taicpu(hp2).opsize = S_Q) and
  5832. (
  5833. (
  5834. MatchInstruction(hp2, A_ADD,[]) and
  5835. (taicpu(hp2).opsize = S_Q) and
  5836. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  5837. (
  5838. (
  5839. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  5840. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5841. ) or (
  5842. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5843. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  5844. )
  5845. )
  5846. ) or (
  5847. MatchInstruction(hp2, A_LEA,[]) and
  5848. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  5849. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  5850. (
  5851. (
  5852. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  5853. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5854. ) or (
  5855. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5856. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  5857. )
  5858. ) and (
  5859. (
  5860. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5861. ) or (
  5862. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  5863. )
  5864. )
  5865. )
  5866. )
  5867. ) and (
  5868. GetNextInstruction(hp2, hp3) and
  5869. MatchInstruction(hp3, A_SHR,[]) and
  5870. (taicpu(hp3).opsize = S_Q) and
  5871. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  5872. (taicpu(hp3).oper[0]^.val = 1) and
  5873. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  5874. ) then
  5875. begin
  5876. { Change movl x, reg1d movl x, reg1d
  5877. movl y, reg2d movl y, reg2d
  5878. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  5879. shrq $1, reg1q shrq $1, reg1q
  5880. ( reg1d and reg2d can be switched around in the first two instructions )
  5881. To movl x, reg1d
  5882. addl y, reg1d
  5883. rcrl $1, reg1d
  5884. This corresponds to the common expression (x + y) shr 1, where
  5885. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  5886. smaller code, but won't account for x + y causing an overflow). [Kit]
  5887. }
  5888. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  5889. { Change first MOV command to have the same register as the final output }
  5890. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  5891. else
  5892. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  5893. { Change second MOV command to an ADD command. This is easier than
  5894. converting the existing command because it means we don't have to
  5895. touch 'y', which might be a complicated reference, and also the
  5896. fact that the third command might either be ADD or LEA. [Kit] }
  5897. taicpu(hp1).opcode := A_ADD;
  5898. { Delete old ADD/LEA instruction }
  5899. RemoveInstruction(hp2);
  5900. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  5901. taicpu(hp3).opcode := A_RCR;
  5902. taicpu(hp3).changeopsize(S_L);
  5903. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  5904. {$endif x86_64}
  5905. end;
  5906. end;
  5907. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  5908. var
  5909. ThisReg: TRegister;
  5910. MinSize, MaxSize, TrySmaller, TargetSize: TOpSize;
  5911. TargetSubReg: TSubRegister;
  5912. hp1, hp2: tai;
  5913. RegInUse, RegChanged, p_removed: Boolean;
  5914. { Store list of found instructions so we don't have to call
  5915. GetNextInstructionUsingReg multiple times }
  5916. InstrList: array of taicpu;
  5917. InstrMax, Index: Integer;
  5918. UpperLimit, TrySmallerLimit: TCgInt;
  5919. PreMessage: string;
  5920. { Data flow analysis }
  5921. TestValMin, TestValMax: TCgInt;
  5922. SmallerOverflow: Boolean;
  5923. begin
  5924. Result := False;
  5925. p_removed := False;
  5926. { This is anything but quick! }
  5927. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  5928. Exit;
  5929. SetLength(InstrList, 0);
  5930. InstrMax := -1;
  5931. ThisReg := taicpu(p).oper[1]^.reg;
  5932. case taicpu(p).opsize of
  5933. S_BW, S_BL:
  5934. begin
  5935. {$if defined(i386) or defined(i8086)}
  5936. { If the target size is 8-bit, make sure we can actually encode it }
  5937. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  5938. Exit;
  5939. {$endif i386 or i8086}
  5940. UpperLimit := $FF;
  5941. MinSize := S_B;
  5942. if taicpu(p).opsize = S_BW then
  5943. MaxSize := S_W
  5944. else
  5945. MaxSize := S_L;
  5946. end;
  5947. S_WL:
  5948. begin
  5949. UpperLimit := $FFFF;
  5950. MinSize := S_W;
  5951. MaxSize := S_L;
  5952. end
  5953. else
  5954. InternalError(2020112301);
  5955. end;
  5956. TestValMin := 0;
  5957. TestValMax := UpperLimit;
  5958. TrySmallerLimit := UpperLimit;
  5959. TrySmaller := S_NO;
  5960. SmallerOverflow := False;
  5961. RegChanged := False;
  5962. hp1 := p;
  5963. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  5964. (hp1.typ = ait_instruction) and
  5965. (
  5966. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  5967. instruction that doesn't actually contain ThisReg }
  5968. (cs_opt_level3 in current_settings.optimizerswitches) or
  5969. RegInInstruction(ThisReg, hp1)
  5970. ) do
  5971. begin
  5972. case taicpu(hp1).opcode of
  5973. A_INC,A_DEC:
  5974. begin
  5975. { Has to be an exact match on the register }
  5976. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  5977. Break;
  5978. if taicpu(hp1).opcode = A_INC then
  5979. begin
  5980. Inc(TestValMin);
  5981. Inc(TestValMax);
  5982. end
  5983. else
  5984. begin
  5985. Dec(TestValMin);
  5986. Dec(TestValMax);
  5987. end;
  5988. end;
  5989. A_CMP:
  5990. begin
  5991. if (taicpu(hp1).oper[1]^.typ <> top_reg) or
  5992. { Has to be an exact match on the register }
  5993. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  5994. (taicpu(hp1).oper[0]^.typ <> top_const) or
  5995. { Make sure the comparison value is not smaller than the
  5996. smallest allowed signed value for the minimum size (e.g.
  5997. -128 for 8-bit) }
  5998. not (
  5999. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6000. { Is it in the negative range? }
  6001. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6002. ) then
  6003. Break;
  6004. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6005. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6006. if (TestValMin < TrySmallerLimit) or (TestValMax < TrySmallerLimit) or
  6007. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6008. { Overflow }
  6009. Break;
  6010. { Check to see if the active register is used afterwards }
  6011. TransferUsedRegs(TmpUsedRegs);
  6012. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  6013. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6014. begin
  6015. case MinSize of
  6016. S_B:
  6017. TargetSubReg := R_SUBL;
  6018. S_W:
  6019. TargetSubReg := R_SUBW;
  6020. else
  6021. InternalError(2021051002);
  6022. end;
  6023. { Update the register to its new size }
  6024. setsubreg(ThisReg, TargetSubReg);
  6025. taicpu(hp1).oper[1]^.reg := ThisReg;
  6026. taicpu(hp1).opsize := MinSize;
  6027. { Convert the input MOVZX to a MOV }
  6028. if (taicpu(p).oper[0]^.typ = top_reg) and
  6029. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6030. begin
  6031. { Or remove it completely! }
  6032. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  6033. RemoveCurrentP(p);
  6034. p_removed := True;
  6035. end
  6036. else
  6037. begin
  6038. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  6039. taicpu(p).opcode := A_MOV;
  6040. taicpu(p).oper[1]^.reg := ThisReg;
  6041. taicpu(p).opsize := MinSize;
  6042. end;
  6043. if (InstrMax >= 0) then
  6044. begin
  6045. for Index := 0 to InstrMax do
  6046. begin
  6047. { If p_removed is true, then the original MOV/Z was removed
  6048. and removing the AND instruction may not be safe if it
  6049. appears first }
  6050. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6051. InternalError(2020112311);
  6052. if InstrList[Index].oper[0]^.typ = top_reg then
  6053. InstrList[Index].oper[0]^.reg := ThisReg;
  6054. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6055. InstrList[Index].opsize := MinSize;
  6056. end;
  6057. end;
  6058. Result := True;
  6059. Exit;
  6060. end;
  6061. end;
  6062. { OR and XOR are not included because they can too easily fool
  6063. the data flow analysis (they can cause non-linear behaviour) }
  6064. A_ADD,A_SUB,A_AND,A_SHL,A_SHR:
  6065. begin
  6066. if
  6067. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6068. { Has to be an exact match on the register }
  6069. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  6070. (
  6071. (
  6072. (taicpu(hp1).oper[0]^.typ = top_const) and
  6073. (
  6074. (
  6075. (taicpu(hp1).opcode = A_SHL) and
  6076. (
  6077. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  6078. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  6079. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  6080. )
  6081. ) or (
  6082. (taicpu(hp1).opcode <> A_SHL) and
  6083. (
  6084. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6085. { Is it in the negative range? }
  6086. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6087. )
  6088. )
  6089. )
  6090. ) or (
  6091. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  6092. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  6093. )
  6094. ) then
  6095. Break;
  6096. case taicpu(hp1).opcode of
  6097. A_ADD:
  6098. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6099. begin
  6100. TestValMin := TestValMin * 2;
  6101. TestValMax := TestValMax * 2;
  6102. end
  6103. else
  6104. begin
  6105. TestValMin := TestValMin + taicpu(hp1).oper[0]^.val;
  6106. TestValMax := TestValMax + taicpu(hp1).oper[0]^.val;
  6107. end;
  6108. A_SUB:
  6109. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6110. begin
  6111. TestValMin := 0;
  6112. TestValMax := 0;
  6113. end
  6114. else
  6115. begin
  6116. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6117. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6118. end;
  6119. A_AND:
  6120. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6121. begin
  6122. { we might be able to go smaller if AND appears first }
  6123. if InstrMax = -1 then
  6124. case MinSize of
  6125. S_B:
  6126. ;
  6127. S_W:
  6128. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6129. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6130. begin
  6131. TrySmaller := S_B;
  6132. TrySmallerLimit := $FF;
  6133. end;
  6134. S_L:
  6135. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6136. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6137. begin
  6138. TrySmaller := S_B;
  6139. TrySmallerLimit := $FF;
  6140. end
  6141. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  6142. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  6143. begin
  6144. TrySmaller := S_W;
  6145. TrySmallerLimit := $FFFF;
  6146. end;
  6147. else
  6148. InternalError(2020112320);
  6149. end;
  6150. TestValMin := TestValMin and taicpu(hp1).oper[0]^.val;
  6151. TestValMax := TestValMax and taicpu(hp1).oper[0]^.val;
  6152. end;
  6153. A_SHL:
  6154. begin
  6155. TestValMin := TestValMin shl taicpu(hp1).oper[0]^.val;
  6156. TestValMax := TestValMax shl taicpu(hp1).oper[0]^.val;
  6157. end;
  6158. A_SHR:
  6159. begin
  6160. { we might be able to go smaller if SHR appears first }
  6161. if InstrMax = -1 then
  6162. case MinSize of
  6163. S_B:
  6164. ;
  6165. S_W:
  6166. if (taicpu(hp1).oper[0]^.val >= 8) then
  6167. begin
  6168. TrySmaller := S_B;
  6169. TrySmallerLimit := $FF;
  6170. end;
  6171. S_L:
  6172. if (taicpu(hp1).oper[0]^.val >= 24) then
  6173. begin
  6174. TrySmaller := S_B;
  6175. TrySmallerLimit := $FF;
  6176. end
  6177. else if (taicpu(hp1).oper[0]^.val >= 16) then
  6178. begin
  6179. TrySmaller := S_W;
  6180. TrySmallerLimit := $FFFF;
  6181. end;
  6182. else
  6183. InternalError(2020112321);
  6184. end;
  6185. TestValMin := TestValMin shr taicpu(hp1).oper[0]^.val;
  6186. TestValMax := TestValMax shr taicpu(hp1).oper[0]^.val;
  6187. end;
  6188. else
  6189. InternalError(2020112303);
  6190. end;
  6191. end;
  6192. (*
  6193. A_IMUL:
  6194. case taicpu(hp1).ops of
  6195. 2:
  6196. begin
  6197. if not MatchOpType(hp1, top_reg, top_reg) or
  6198. { Has to be an exact match on the register }
  6199. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  6200. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  6201. Break;
  6202. TestValMin := TestValMin * TestValMin;
  6203. TestValMax := TestValMax * TestValMax;
  6204. end;
  6205. 3:
  6206. begin
  6207. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6208. { Has to be an exact match on the register }
  6209. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6210. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6211. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6212. { Is it in the negative range? }
  6213. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6214. Break;
  6215. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  6216. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  6217. end;
  6218. else
  6219. Break;
  6220. end;
  6221. A_IDIV:
  6222. case taicpu(hp1).ops of
  6223. 3:
  6224. begin
  6225. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6226. { Has to be an exact match on the register }
  6227. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6228. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6229. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6230. { Is it in the negative range? }
  6231. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6232. Break;
  6233. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  6234. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  6235. end;
  6236. else
  6237. Break;
  6238. end;
  6239. *)
  6240. A_MOVZX:
  6241. begin
  6242. if not MatchOpType(taicpu(hp1), top_reg, top_reg) then
  6243. Break;
  6244. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  6245. begin
  6246. { Because hp1 was obtained via GetNextInstructionUsingReg
  6247. and ThisReg doesn't appear in the first operand, it
  6248. must appear in the second operand and hence gets
  6249. overwritten }
  6250. if (InstrMax = -1) and
  6251. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6252. begin
  6253. { The two MOVZX instructions are adjacent, so remove the first one }
  6254. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  6255. RemoveCurrentP(p);
  6256. Result := True;
  6257. Exit;
  6258. end;
  6259. Break;
  6260. end;
  6261. { The objective here is to try to find a combination that
  6262. removes one of the MOV/Z instructions. }
  6263. case taicpu(hp1).opsize of
  6264. S_WL:
  6265. if (MinSize in [S_B, S_W]) then
  6266. begin
  6267. TargetSize := S_L;
  6268. TargetSubReg := R_SUBD;
  6269. end
  6270. else if ((TrySmaller in [S_B, S_W]) and not SmallerOverflow) then
  6271. begin
  6272. TargetSize := TrySmaller;
  6273. if TrySmaller = S_B then
  6274. TargetSubReg := R_SUBL
  6275. else
  6276. TargetSubReg := R_SUBW;
  6277. end
  6278. else
  6279. Break;
  6280. S_BW:
  6281. if (MinSize in [S_B, S_W]) then
  6282. begin
  6283. TargetSize := S_W;
  6284. TargetSubReg := R_SUBW;
  6285. end
  6286. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6287. begin
  6288. TargetSize := S_B;
  6289. TargetSubReg := R_SUBL;
  6290. end
  6291. else
  6292. Break;
  6293. S_BL:
  6294. if (MinSize in [S_B, S_W]) then
  6295. begin
  6296. TargetSize := S_L;
  6297. TargetSubReg := R_SUBD;
  6298. end
  6299. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6300. begin
  6301. TargetSize := S_B;
  6302. TargetSubReg := R_SUBL;
  6303. end
  6304. else
  6305. Break;
  6306. else
  6307. InternalError(2020112302);
  6308. end;
  6309. { Update the register to its new size }
  6310. setsubreg(ThisReg, TargetSubReg);
  6311. if TargetSize = MinSize then
  6312. begin
  6313. { Convert the input MOVZX to a MOV }
  6314. if (taicpu(p).oper[0]^.typ = top_reg) and
  6315. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6316. begin
  6317. { Or remove it completely! }
  6318. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  6319. RemoveCurrentP(p);
  6320. p_removed := True;
  6321. end
  6322. else
  6323. begin
  6324. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  6325. taicpu(p).opcode := A_MOV;
  6326. taicpu(p).oper[1]^.reg := ThisReg;
  6327. taicpu(p).opsize := TargetSize;
  6328. end;
  6329. Result := True;
  6330. end
  6331. else if TargetSize <> MaxSize then
  6332. begin
  6333. case MaxSize of
  6334. S_L:
  6335. if TargetSize = S_W then
  6336. begin
  6337. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  6338. taicpu(p).opsize := S_BW;
  6339. taicpu(p).oper[1]^.reg := ThisReg;
  6340. Result := True;
  6341. end
  6342. else
  6343. InternalError(2020112341);
  6344. S_W:
  6345. if TargetSize = S_L then
  6346. begin
  6347. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  6348. taicpu(p).opsize := S_BL;
  6349. taicpu(p).oper[1]^.reg := ThisReg;
  6350. Result := True;
  6351. end
  6352. else
  6353. InternalError(2020112342);
  6354. else
  6355. ;
  6356. end;
  6357. end;
  6358. if (MaxSize = TargetSize) or
  6359. ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  6360. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  6361. begin
  6362. { Convert the output MOVZX to a MOV }
  6363. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6364. begin
  6365. { Or remove it completely! }
  6366. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  6367. { Be careful; if p = hp1 and p was also removed, p
  6368. will become a dangling pointer }
  6369. if p = hp1 then
  6370. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6371. else
  6372. RemoveInstruction(hp1);
  6373. end
  6374. else
  6375. begin
  6376. taicpu(hp1).opcode := A_MOV;
  6377. taicpu(hp1).oper[0]^.reg := ThisReg;
  6378. taicpu(hp1).opsize := TargetSize;
  6379. { Check to see if the active register is used afterwards;
  6380. if not, we can change it and make a saving. }
  6381. RegInUse := False;
  6382. TransferUsedRegs(TmpUsedRegs);
  6383. { The target register may be marked as in use to cross
  6384. a jump to a distant label, so exclude it }
  6385. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  6386. hp2 := p;
  6387. repeat
  6388. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6389. { Explicitly check for the excluded register (don't include the first
  6390. instruction as it may be reading from here }
  6391. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  6392. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  6393. begin
  6394. RegInUse := True;
  6395. Break;
  6396. end;
  6397. if not GetNextInstruction(hp2, hp2) then
  6398. InternalError(2020112340);
  6399. until (hp2 = hp1);
  6400. if not RegInUse and not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6401. begin
  6402. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  6403. ThisReg := taicpu(hp1).oper[1]^.reg;
  6404. RegChanged := True;
  6405. TransferUsedRegs(TmpUsedRegs);
  6406. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  6407. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  6408. if p = hp1 then
  6409. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6410. else
  6411. RemoveInstruction(hp1);
  6412. { Instruction will become "mov %reg,%reg" }
  6413. if not p_removed and (taicpu(p).opcode = A_MOV) and
  6414. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  6415. begin
  6416. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  6417. RemoveCurrentP(p);
  6418. p_removed := True;
  6419. end
  6420. else
  6421. taicpu(p).oper[1]^.reg := ThisReg;
  6422. Result := True;
  6423. end
  6424. else
  6425. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  6426. end;
  6427. end
  6428. else
  6429. InternalError(2020112330);
  6430. { Now go through every instruction we found and change the
  6431. size. If TargetSize = MaxSize, then almost no changes are
  6432. needed and Result can remain False if it hasn't been set
  6433. yet.
  6434. If RegChanged is True, then the register requires changing
  6435. and so the point about TargetSize = MaxSize doesn't apply. }
  6436. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  6437. begin
  6438. for Index := 0 to InstrMax do
  6439. begin
  6440. { If p_removed is true, then the original MOV/Z was removed
  6441. and removing the AND instruction may not be safe if it
  6442. appears first }
  6443. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6444. InternalError(2020112310);
  6445. if InstrList[Index].oper[0]^.typ = top_reg then
  6446. InstrList[Index].oper[0]^.reg := ThisReg;
  6447. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6448. InstrList[Index].opsize := TargetSize;
  6449. end;
  6450. Result := True;
  6451. end;
  6452. Exit;
  6453. end;
  6454. else
  6455. { This includes ADC, SBB, IDIV and SAR }
  6456. Break;
  6457. end;
  6458. if (TestValMin < 0) or (TestValMax < 0) or
  6459. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6460. { Overflow }
  6461. Break
  6462. else if not SmallerOverflow and (TrySmaller <> S_NO) and
  6463. ((TestValMin > TrySmallerLimit) or (TestValMax > TrySmallerLimit)) then
  6464. SmallerOverflow := True;
  6465. { Contains highest index (so instruction count - 1) }
  6466. Inc(InstrMax);
  6467. if InstrMax > High(InstrList) then
  6468. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6469. InstrList[InstrMax] := taicpu(hp1);
  6470. end;
  6471. end;
  6472. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  6473. var
  6474. hp1 : tai;
  6475. begin
  6476. Result:=false;
  6477. if (taicpu(p).ops >= 2) and
  6478. ((taicpu(p).oper[0]^.typ = top_const) or
  6479. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  6480. (taicpu(p).oper[1]^.typ = top_reg) and
  6481. ((taicpu(p).ops = 2) or
  6482. ((taicpu(p).oper[2]^.typ = top_reg) and
  6483. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  6484. GetLastInstruction(p,hp1) and
  6485. MatchInstruction(hp1,A_MOV,[]) and
  6486. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6487. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6488. begin
  6489. TransferUsedRegs(TmpUsedRegs);
  6490. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  6491. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  6492. { change
  6493. mov reg1,reg2
  6494. imul y,reg2 to imul y,reg1,reg2 }
  6495. begin
  6496. taicpu(p).ops := 3;
  6497. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  6498. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6499. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  6500. RemoveInstruction(hp1);
  6501. result:=true;
  6502. end;
  6503. end;
  6504. end;
  6505. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  6506. var
  6507. ThisLabel: TAsmLabel;
  6508. begin
  6509. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  6510. ThisLabel.decrefs;
  6511. taicpu(p).opcode := A_RET;
  6512. taicpu(p).is_jmp := false;
  6513. taicpu(p).ops := taicpu(ret_p).ops;
  6514. case taicpu(ret_p).ops of
  6515. 0:
  6516. taicpu(p).clearop(0);
  6517. 1:
  6518. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  6519. else
  6520. internalerror(2016041301);
  6521. end;
  6522. { If the original label is now dead, it might turn out that the label
  6523. immediately follows p. As a result, everything beyond it, which will
  6524. be just some final register configuration and a RET instruction, is
  6525. now dead code. [Kit] }
  6526. { NOTE: This is much faster than introducing a OptPass2RET routine and
  6527. running RemoveDeadCodeAfterJump for each RET instruction, because
  6528. this optimisation rarely happens and most RETs appear at the end of
  6529. routines where there is nothing that can be stripped. [Kit] }
  6530. if not ThisLabel.is_used then
  6531. RemoveDeadCodeAfterJump(p);
  6532. end;
  6533. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  6534. var
  6535. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  6536. Unconditional, PotentialModified: Boolean;
  6537. OperPtr: POper;
  6538. NewRef: TReference;
  6539. InstrList: array of taicpu;
  6540. InstrMax, Index: Integer;
  6541. const
  6542. {$ifdef DEBUG_AOPTCPU}
  6543. SNoFlags: shortstring = ' so the flags aren''t modified';
  6544. {$else DEBUG_AOPTCPU}
  6545. SNoFlags = '';
  6546. {$endif DEBUG_AOPTCPU}
  6547. begin
  6548. Result:=false;
  6549. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  6550. begin
  6551. if MatchInstruction(hp1, A_TEST, [S_B]) and
  6552. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6553. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6554. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6555. GetNextInstruction(hp1, hp2) and
  6556. MatchInstruction(hp2, A_Jcc, []) then
  6557. { Change from: To:
  6558. set(C) %reg j(~C) label
  6559. test %reg,%reg/cmp $0,%reg
  6560. je label
  6561. set(C) %reg j(C) label
  6562. test %reg,%reg/cmp $0,%reg
  6563. jne label
  6564. }
  6565. begin
  6566. { Before we do anything else, we need to check the instructions
  6567. in between SETcc and TEST to make sure they don't modify the
  6568. FLAGS register - if -O2 or under, there won't be any
  6569. instructions between SET and TEST }
  6570. TransferUsedRegs(TmpUsedRegs);
  6571. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6572. if (cs_opt_level3 in current_settings.optimizerswitches) then
  6573. begin
  6574. next := p;
  6575. SetLength(InstrList, 0);
  6576. InstrMax := -1;
  6577. PotentialModified := False;
  6578. { Make a note of every instruction that modifies the FLAGS
  6579. register }
  6580. while GetNextInstruction(next, next) and (next <> hp1) do
  6581. begin
  6582. if next.typ <> ait_instruction then
  6583. { GetNextInstructionUsingReg should have returned False }
  6584. InternalError(2021051701);
  6585. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  6586. begin
  6587. case taicpu(next).opcode of
  6588. A_SETcc,
  6589. A_CMOVcc,
  6590. A_Jcc:
  6591. begin
  6592. if PotentialModified then
  6593. { Not safe because the flags were modified earlier }
  6594. Exit
  6595. else
  6596. { Condition is the same as the initial SETcc, so this is safe
  6597. (don't add to instruction list though) }
  6598. Continue;
  6599. end;
  6600. A_ADD:
  6601. begin
  6602. if (taicpu(next).opsize = S_B) or
  6603. { LEA doesn't support 8-bit operands }
  6604. (taicpu(next).oper[1]^.typ <> top_reg) or
  6605. { Must write to a register }
  6606. (taicpu(next).oper[0]^.typ = top_ref) then
  6607. { Require a constant or a register }
  6608. Exit;
  6609. PotentialModified := True;
  6610. end;
  6611. A_SUB:
  6612. begin
  6613. if (taicpu(next).opsize = S_B) or
  6614. { LEA doesn't support 8-bit operands }
  6615. (taicpu(next).oper[1]^.typ <> top_reg) or
  6616. { Must write to a register }
  6617. (taicpu(next).oper[0]^.typ <> top_const) or
  6618. (taicpu(next).oper[0]^.val = $80000000) then
  6619. { Can't subtract a register with LEA - also
  6620. check that the value isn't -2^31, as this
  6621. can't be negated }
  6622. Exit;
  6623. PotentialModified := True;
  6624. end;
  6625. A_SAL,
  6626. A_SHL:
  6627. begin
  6628. if (taicpu(next).opsize = S_B) or
  6629. { LEA doesn't support 8-bit operands }
  6630. (taicpu(next).oper[1]^.typ <> top_reg) or
  6631. { Must write to a register }
  6632. (taicpu(next).oper[0]^.typ <> top_const) or
  6633. (taicpu(next).oper[0]^.val < 0) or
  6634. (taicpu(next).oper[0]^.val > 3) then
  6635. Exit;
  6636. PotentialModified := True;
  6637. end;
  6638. A_IMUL:
  6639. begin
  6640. if (taicpu(next).ops <> 3) or
  6641. (taicpu(next).oper[1]^.typ <> top_reg) or
  6642. { Must write to a register }
  6643. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  6644. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  6645. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  6646. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  6647. Exit
  6648. else
  6649. PotentialModified := True;
  6650. end;
  6651. else
  6652. { Don't know how to change this, so abort }
  6653. Exit;
  6654. end;
  6655. { Contains highest index (so instruction count - 1) }
  6656. Inc(InstrMax);
  6657. if InstrMax > High(InstrList) then
  6658. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6659. InstrList[InstrMax] := taicpu(next);
  6660. end;
  6661. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  6662. end;
  6663. if not Assigned(next) or (next <> hp1) then
  6664. { It should be equal to hp1 }
  6665. InternalError(2021051702);
  6666. { Cycle through each instruction and check to see if we can
  6667. change them to versions that don't modify the flags }
  6668. if (InstrMax >= 0) then
  6669. begin
  6670. for Index := 0 to InstrMax do
  6671. case InstrList[Index].opcode of
  6672. A_ADD:
  6673. begin
  6674. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  6675. InstrList[Index].opcode := A_LEA;
  6676. reference_reset(NewRef, 1, []);
  6677. NewRef.base := InstrList[Index].oper[1]^.reg;
  6678. if InstrList[Index].oper[0]^.typ = top_reg then
  6679. begin
  6680. NewRef.index := InstrList[Index].oper[0]^.reg;
  6681. NewRef.scalefactor := 1;
  6682. end
  6683. else
  6684. NewRef.offset := InstrList[Index].oper[0]^.val;
  6685. InstrList[Index].loadref(0, NewRef);
  6686. end;
  6687. A_SUB:
  6688. begin
  6689. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  6690. InstrList[Index].opcode := A_LEA;
  6691. reference_reset(NewRef, 1, []);
  6692. NewRef.base := InstrList[Index].oper[1]^.reg;
  6693. NewRef.offset := -InstrList[Index].oper[0]^.val;
  6694. InstrList[Index].loadref(0, NewRef);
  6695. end;
  6696. A_SHL,
  6697. A_SAL:
  6698. begin
  6699. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  6700. InstrList[Index].opcode := A_LEA;
  6701. reference_reset(NewRef, 1, []);
  6702. NewRef.index := InstrList[Index].oper[1]^.reg;
  6703. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  6704. InstrList[Index].loadref(0, NewRef);
  6705. end;
  6706. A_IMUL:
  6707. begin
  6708. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  6709. InstrList[Index].opcode := A_LEA;
  6710. reference_reset(NewRef, 1, []);
  6711. NewRef.index := InstrList[Index].oper[1]^.reg;
  6712. case InstrList[Index].oper[0]^.val of
  6713. 2, 4, 8:
  6714. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  6715. else {3, 5 and 9}
  6716. begin
  6717. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  6718. NewRef.base := InstrList[Index].oper[1]^.reg;
  6719. end;
  6720. end;
  6721. InstrList[Index].loadref(0, NewRef);
  6722. end;
  6723. else
  6724. InternalError(2021051710);
  6725. end;
  6726. end;
  6727. { Mark the FLAGS register as used across this whole block }
  6728. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  6729. end;
  6730. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6731. JumpC := taicpu(hp2).condition;
  6732. Unconditional := False;
  6733. if conditions_equal(JumpC, C_E) then
  6734. SetC := inverse_cond(taicpu(p).condition)
  6735. else if conditions_equal(JumpC, C_NE) then
  6736. SetC := taicpu(p).condition
  6737. else
  6738. { We've got something weird here (and inefficent) }
  6739. begin
  6740. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  6741. SetC := C_NONE;
  6742. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  6743. if condition_in(C_AE, JumpC) then
  6744. Unconditional := True
  6745. else
  6746. { Not sure what to do with this jump - drop out }
  6747. Exit;
  6748. end;
  6749. RemoveInstruction(hp1);
  6750. if Unconditional then
  6751. MakeUnconditional(taicpu(hp2))
  6752. else
  6753. begin
  6754. if SetC = C_NONE then
  6755. InternalError(2018061402);
  6756. taicpu(hp2).SetCondition(SetC);
  6757. end;
  6758. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  6759. TmpUsedRegs }
  6760. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  6761. begin
  6762. RemoveCurrentp(p, hp2);
  6763. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  6764. end
  6765. else
  6766. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  6767. Result := True;
  6768. end
  6769. else if
  6770. { Make sure the instructions are adjacent }
  6771. (
  6772. not (cs_opt_level3 in current_settings.optimizerswitches) or
  6773. GetNextInstruction(p, hp1)
  6774. ) and
  6775. MatchInstruction(hp1, A_MOV, [S_B]) and
  6776. { Writing to memory is allowed }
  6777. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  6778. begin
  6779. {
  6780. Watch out for sequences such as:
  6781. set(c)b %regb
  6782. movb %regb,(ref)
  6783. movb $0,1(ref)
  6784. movb $0,2(ref)
  6785. movb $0,3(ref)
  6786. Much more efficient to turn it into:
  6787. movl $0,%regl
  6788. set(c)b %regb
  6789. movl %regl,(ref)
  6790. Or:
  6791. set(c)b %regb
  6792. movzbl %regb,%regl
  6793. movl %regl,(ref)
  6794. }
  6795. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  6796. GetNextInstruction(hp1, hp2) and
  6797. MatchInstruction(hp2, A_MOV, [S_B]) and
  6798. (taicpu(hp2).oper[1]^.typ = top_ref) and
  6799. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  6800. begin
  6801. { Don't do anything else except set Result to True }
  6802. end
  6803. else
  6804. begin
  6805. if taicpu(p).oper[0]^.typ = top_reg then
  6806. begin
  6807. TransferUsedRegs(TmpUsedRegs);
  6808. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6809. end;
  6810. { If it's not a register, it's a memory address }
  6811. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  6812. begin
  6813. { Even if the register is still in use, we can minimise the
  6814. pipeline stall by changing the MOV into another SETcc. }
  6815. taicpu(hp1).opcode := A_SETcc;
  6816. taicpu(hp1).condition := taicpu(p).condition;
  6817. if taicpu(hp1).oper[1]^.typ = top_ref then
  6818. begin
  6819. { Swapping the operand pointers like this is probably a
  6820. bit naughty, but it is far faster than using loadoper
  6821. to transfer the reference from oper[1] to oper[0] if
  6822. you take into account the extra procedure calls and
  6823. the memory allocation and deallocation required }
  6824. OperPtr := taicpu(hp1).oper[1];
  6825. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  6826. taicpu(hp1).oper[0] := OperPtr;
  6827. end
  6828. else
  6829. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  6830. taicpu(hp1).clearop(1);
  6831. taicpu(hp1).ops := 1;
  6832. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  6833. end
  6834. else
  6835. begin
  6836. if taicpu(hp1).oper[1]^.typ = top_reg then
  6837. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  6838. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6839. RemoveInstruction(hp1);
  6840. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  6841. end
  6842. end;
  6843. Result := True;
  6844. end;
  6845. end;
  6846. end;
  6847. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  6848. var
  6849. hp1: tai;
  6850. Count: Integer;
  6851. OrigLabel: TAsmLabel;
  6852. begin
  6853. result := False;
  6854. { Sometimes, the optimisations below can permit this }
  6855. RemoveDeadCodeAfterJump(p);
  6856. 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
  6857. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  6858. begin
  6859. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6860. { Also a side-effect of optimisations }
  6861. if CollapseZeroDistJump(p, OrigLabel) then
  6862. begin
  6863. Result := True;
  6864. Exit;
  6865. end;
  6866. hp1 := GetLabelWithSym(OrigLabel);
  6867. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  6868. begin
  6869. case taicpu(hp1).opcode of
  6870. A_RET:
  6871. {
  6872. change
  6873. jmp .L1
  6874. ...
  6875. .L1:
  6876. ret
  6877. into
  6878. ret
  6879. }
  6880. begin
  6881. ConvertJumpToRET(p, hp1);
  6882. result:=true;
  6883. end;
  6884. { Check any kind of direct assignment instruction }
  6885. A_MOV,
  6886. A_MOVD,
  6887. A_MOVQ,
  6888. A_MOVSX,
  6889. {$ifdef x86_64}
  6890. A_MOVSXD,
  6891. {$endif x86_64}
  6892. A_MOVZX,
  6893. A_MOVAPS,
  6894. A_MOVUPS,
  6895. A_MOVSD,
  6896. A_MOVAPD,
  6897. A_MOVUPD,
  6898. A_MOVDQA,
  6899. A_MOVDQU,
  6900. A_VMOVSS,
  6901. A_VMOVAPS,
  6902. A_VMOVUPS,
  6903. A_VMOVSD,
  6904. A_VMOVAPD,
  6905. A_VMOVUPD,
  6906. A_VMOVDQA,
  6907. A_VMOVDQU:
  6908. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  6909. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  6910. begin
  6911. Result := True;
  6912. Exit;
  6913. end;
  6914. else
  6915. ;
  6916. end;
  6917. end;
  6918. end;
  6919. end;
  6920. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  6921. begin
  6922. CanBeCMOV:=assigned(p) and
  6923. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  6924. { we can't use cmov ref,reg because
  6925. ref could be nil and cmov still throws an exception
  6926. if ref=nil but the mov isn't done (FK)
  6927. or ((taicpu(p).oper[0]^.typ = top_ref) and
  6928. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  6929. }
  6930. (taicpu(p).oper[1]^.typ = top_reg) and
  6931. (
  6932. (taicpu(p).oper[0]^.typ = top_reg) or
  6933. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  6934. it is not expected that this can cause a seg. violation }
  6935. (
  6936. (taicpu(p).oper[0]^.typ = top_ref) and
  6937. IsRefSafe(taicpu(p).oper[0]^.ref)
  6938. )
  6939. );
  6940. end;
  6941. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  6942. var
  6943. hp1,hp2: tai;
  6944. {$ifndef i8086}
  6945. hp3,hp4,hpmov2, hp5: tai;
  6946. l : Longint;
  6947. condition : TAsmCond;
  6948. {$endif i8086}
  6949. carryadd_opcode : TAsmOp;
  6950. symbol: TAsmSymbol;
  6951. reg: tsuperregister;
  6952. increg, tmpreg: TRegister;
  6953. begin
  6954. result:=false;
  6955. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  6956. begin
  6957. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6958. if (
  6959. (
  6960. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  6961. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  6962. (Taicpu(hp1).oper[0]^.val=1)
  6963. ) or
  6964. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  6965. ) and
  6966. GetNextInstruction(hp1,hp2) and
  6967. SkipAligns(hp2, hp2) and
  6968. (hp2.typ = ait_label) and
  6969. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  6970. { jb @@1 cmc
  6971. inc/dec operand --> adc/sbb operand,0
  6972. @@1:
  6973. ... and ...
  6974. jnb @@1
  6975. inc/dec operand --> adc/sbb operand,0
  6976. @@1: }
  6977. begin
  6978. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  6979. begin
  6980. case taicpu(hp1).opcode of
  6981. A_INC,
  6982. A_ADD:
  6983. carryadd_opcode:=A_ADC;
  6984. A_DEC,
  6985. A_SUB:
  6986. carryadd_opcode:=A_SBB;
  6987. else
  6988. InternalError(2021011001);
  6989. end;
  6990. Taicpu(p).clearop(0);
  6991. Taicpu(p).ops:=0;
  6992. Taicpu(p).is_jmp:=false;
  6993. Taicpu(p).opcode:=A_CMC;
  6994. Taicpu(p).condition:=C_NONE;
  6995. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  6996. Taicpu(hp1).ops:=2;
  6997. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  6998. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  6999. else
  7000. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7001. Taicpu(hp1).loadconst(0,0);
  7002. Taicpu(hp1).opcode:=carryadd_opcode;
  7003. result:=true;
  7004. exit;
  7005. end
  7006. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  7007. begin
  7008. case taicpu(hp1).opcode of
  7009. A_INC,
  7010. A_ADD:
  7011. carryadd_opcode:=A_ADC;
  7012. A_DEC,
  7013. A_SUB:
  7014. carryadd_opcode:=A_SBB;
  7015. else
  7016. InternalError(2021011002);
  7017. end;
  7018. Taicpu(hp1).ops:=2;
  7019. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  7020. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  7021. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7022. else
  7023. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7024. Taicpu(hp1).loadconst(0,0);
  7025. Taicpu(hp1).opcode:=carryadd_opcode;
  7026. RemoveCurrentP(p, hp1);
  7027. result:=true;
  7028. exit;
  7029. end
  7030. {
  7031. jcc @@1 setcc tmpreg
  7032. inc/dec/add/sub operand -> (movzx tmpreg)
  7033. @@1: add/sub tmpreg,operand
  7034. While this increases code size slightly, it makes the code much faster if the
  7035. jump is unpredictable
  7036. }
  7037. else if not(cs_opt_size in current_settings.optimizerswitches) then
  7038. begin
  7039. { search for an available register which is volatile }
  7040. for reg in tcpuregisterset do
  7041. begin
  7042. if
  7043. {$if defined(i386) or defined(i8086)}
  7044. { Only use registers whose lowest 8-bits can Be accessed }
  7045. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  7046. {$endif i386 or i8086}
  7047. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  7048. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  7049. { We don't need to check if tmpreg is in hp1 or not, because
  7050. it will be marked as in use at p (if not, this is
  7051. indictive of a compiler bug). }
  7052. then
  7053. begin
  7054. TAsmLabel(symbol).decrefs;
  7055. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  7056. Taicpu(p).clearop(0);
  7057. Taicpu(p).ops:=1;
  7058. Taicpu(p).is_jmp:=false;
  7059. Taicpu(p).opcode:=A_SETcc;
  7060. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  7061. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  7062. Taicpu(p).loadreg(0,increg);
  7063. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  7064. begin
  7065. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  7066. R_SUBW:
  7067. begin
  7068. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  7069. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  7070. end;
  7071. R_SUBD:
  7072. begin
  7073. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  7074. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  7075. end;
  7076. {$ifdef x86_64}
  7077. R_SUBQ:
  7078. begin
  7079. { MOVZX doesn't have a 64-bit variant, because
  7080. the 32-bit version implicitly zeroes the
  7081. upper 32-bits of the destination register }
  7082. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  7083. newreg(R_INTREGISTER,reg,R_SUBD));
  7084. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  7085. end;
  7086. {$endif x86_64}
  7087. else
  7088. Internalerror(2020030601);
  7089. end;
  7090. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  7091. asml.InsertAfter(hp2,p);
  7092. end
  7093. else
  7094. tmpreg := increg;
  7095. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  7096. begin
  7097. Taicpu(hp1).ops:=2;
  7098. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  7099. end;
  7100. Taicpu(hp1).loadreg(0,tmpreg);
  7101. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  7102. Result := True;
  7103. { p is no longer a Jcc instruction, so exit }
  7104. Exit;
  7105. end;
  7106. end;
  7107. end;
  7108. end;
  7109. { Detect the following:
  7110. jmp<cond> @Lbl1
  7111. jmp @Lbl2
  7112. ...
  7113. @Lbl1:
  7114. ret
  7115. Change to:
  7116. jmp<inv_cond> @Lbl2
  7117. ret
  7118. }
  7119. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  7120. begin
  7121. hp2:=getlabelwithsym(TAsmLabel(symbol));
  7122. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  7123. MatchInstruction(hp2,A_RET,[S_NO]) then
  7124. begin
  7125. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7126. { Change label address to that of the unconditional jump }
  7127. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  7128. TAsmLabel(symbol).DecRefs;
  7129. taicpu(hp1).opcode := A_RET;
  7130. taicpu(hp1).is_jmp := false;
  7131. taicpu(hp1).ops := taicpu(hp2).ops;
  7132. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  7133. case taicpu(hp2).ops of
  7134. 0:
  7135. taicpu(hp1).clearop(0);
  7136. 1:
  7137. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  7138. else
  7139. internalerror(2016041302);
  7140. end;
  7141. end;
  7142. {$ifndef i8086}
  7143. end
  7144. {
  7145. convert
  7146. j<c> .L1
  7147. mov 1,reg
  7148. jmp .L2
  7149. .L1
  7150. mov 0,reg
  7151. .L2
  7152. into
  7153. mov 0,reg
  7154. set<not(c)> reg
  7155. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7156. would destroy the flag contents
  7157. }
  7158. else if MatchInstruction(hp1,A_MOV,[]) and
  7159. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7160. {$ifdef i386}
  7161. (
  7162. { Under i386, ESI, EDI, EBP and ESP
  7163. don't have an 8-bit representation }
  7164. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7165. ) and
  7166. {$endif i386}
  7167. (taicpu(hp1).oper[0]^.val=1) and
  7168. GetNextInstruction(hp1,hp2) and
  7169. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7170. GetNextInstruction(hp2,hp3) and
  7171. { skip align }
  7172. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  7173. (hp3.typ=ait_label) and
  7174. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7175. (tai_label(hp3).labsym.getrefs=1) and
  7176. GetNextInstruction(hp3,hp4) and
  7177. MatchInstruction(hp4,A_MOV,[]) and
  7178. MatchOpType(taicpu(hp4),top_const,top_reg) and
  7179. (taicpu(hp4).oper[0]^.val=0) and
  7180. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7181. GetNextInstruction(hp4,hp5) and
  7182. (hp5.typ=ait_label) and
  7183. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  7184. (tai_label(hp5).labsym.getrefs=1) then
  7185. begin
  7186. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  7187. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  7188. { remove last label }
  7189. RemoveInstruction(hp5);
  7190. { remove second label }
  7191. RemoveInstruction(hp3);
  7192. { if align is present remove it }
  7193. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  7194. RemoveInstruction(hp3);
  7195. { remove jmp }
  7196. RemoveInstruction(hp2);
  7197. if taicpu(hp1).opsize=S_B then
  7198. RemoveInstruction(hp1)
  7199. else
  7200. taicpu(hp1).loadconst(0,0);
  7201. taicpu(hp4).opcode:=A_SETcc;
  7202. taicpu(hp4).opsize:=S_B;
  7203. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  7204. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  7205. taicpu(hp4).opercnt:=1;
  7206. taicpu(hp4).ops:=1;
  7207. taicpu(hp4).freeop(1);
  7208. RemoveCurrentP(p);
  7209. Result:=true;
  7210. exit;
  7211. end
  7212. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  7213. begin
  7214. { check for
  7215. jCC xxx
  7216. <several movs>
  7217. xxx:
  7218. }
  7219. l:=0;
  7220. while assigned(hp1) and
  7221. CanBeCMOV(hp1) and
  7222. { stop on labels }
  7223. not(hp1.typ=ait_label) do
  7224. begin
  7225. inc(l);
  7226. GetNextInstruction(hp1,hp1);
  7227. end;
  7228. if assigned(hp1) then
  7229. begin
  7230. if FindLabel(tasmlabel(symbol),hp1) then
  7231. begin
  7232. if (l<=4) and (l>0) then
  7233. begin
  7234. condition:=inverse_cond(taicpu(p).condition);
  7235. GetNextInstruction(p,hp1);
  7236. repeat
  7237. if not Assigned(hp1) then
  7238. InternalError(2018062900);
  7239. taicpu(hp1).opcode:=A_CMOVcc;
  7240. taicpu(hp1).condition:=condition;
  7241. UpdateUsedRegs(hp1);
  7242. GetNextInstruction(hp1,hp1);
  7243. until not(CanBeCMOV(hp1));
  7244. { Remember what hp1 is in case there's multiple aligns to get rid of }
  7245. hp2 := hp1;
  7246. repeat
  7247. if not Assigned(hp2) then
  7248. InternalError(2018062910);
  7249. case hp2.typ of
  7250. ait_label:
  7251. { What we expected - break out of the loop (it won't be a dead label at the top of
  7252. a cluster because that was optimised at an earlier stage) }
  7253. Break;
  7254. ait_align:
  7255. { Go to the next entry until a label is found (may be multiple aligns before it) }
  7256. begin
  7257. hp2 := tai(hp2.Next);
  7258. Continue;
  7259. end;
  7260. else
  7261. begin
  7262. { Might be a comment or temporary allocation entry }
  7263. if not (hp2.typ in SkipInstr) then
  7264. InternalError(2018062911);
  7265. hp2 := tai(hp2.Next);
  7266. Continue;
  7267. end;
  7268. end;
  7269. until False;
  7270. { Now we can safely decrement the reference count }
  7271. tasmlabel(symbol).decrefs;
  7272. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  7273. { Remove the original jump }
  7274. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  7275. GetNextInstruction(hp2, p); { Instruction after the label }
  7276. { Remove the label if this is its final reference }
  7277. if (tasmlabel(symbol).getrefs=0) then
  7278. StripLabelFast(hp1);
  7279. if Assigned(p) then
  7280. begin
  7281. UpdateUsedRegs(p);
  7282. result:=true;
  7283. end;
  7284. exit;
  7285. end;
  7286. end
  7287. else
  7288. begin
  7289. { check further for
  7290. jCC xxx
  7291. <several movs 1>
  7292. jmp yyy
  7293. xxx:
  7294. <several movs 2>
  7295. yyy:
  7296. }
  7297. { hp2 points to jmp yyy }
  7298. hp2:=hp1;
  7299. { skip hp1 to xxx (or an align right before it) }
  7300. GetNextInstruction(hp1, hp1);
  7301. if assigned(hp2) and
  7302. assigned(hp1) and
  7303. (l<=3) and
  7304. (hp2.typ=ait_instruction) and
  7305. (taicpu(hp2).is_jmp) and
  7306. (taicpu(hp2).condition=C_None) and
  7307. { real label and jump, no further references to the
  7308. label are allowed }
  7309. (tasmlabel(symbol).getrefs=1) and
  7310. FindLabel(tasmlabel(symbol),hp1) then
  7311. begin
  7312. l:=0;
  7313. { skip hp1 to <several moves 2> }
  7314. if (hp1.typ = ait_align) then
  7315. GetNextInstruction(hp1, hp1);
  7316. GetNextInstruction(hp1, hpmov2);
  7317. hp1 := hpmov2;
  7318. while assigned(hp1) and
  7319. CanBeCMOV(hp1) do
  7320. begin
  7321. inc(l);
  7322. GetNextInstruction(hp1, hp1);
  7323. end;
  7324. { hp1 points to yyy (or an align right before it) }
  7325. hp3 := hp1;
  7326. if assigned(hp1) and
  7327. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  7328. begin
  7329. condition:=inverse_cond(taicpu(p).condition);
  7330. GetNextInstruction(p,hp1);
  7331. repeat
  7332. taicpu(hp1).opcode:=A_CMOVcc;
  7333. taicpu(hp1).condition:=condition;
  7334. UpdateUsedRegs(hp1);
  7335. GetNextInstruction(hp1,hp1);
  7336. until not(assigned(hp1)) or
  7337. not(CanBeCMOV(hp1));
  7338. condition:=inverse_cond(condition);
  7339. hp1 := hpmov2;
  7340. { hp1 is now at <several movs 2> }
  7341. while Assigned(hp1) and CanBeCMOV(hp1) do
  7342. begin
  7343. taicpu(hp1).opcode:=A_CMOVcc;
  7344. taicpu(hp1).condition:=condition;
  7345. UpdateUsedRegs(hp1);
  7346. GetNextInstruction(hp1,hp1);
  7347. end;
  7348. hp1 := p;
  7349. { Get first instruction after label }
  7350. GetNextInstruction(hp3, p);
  7351. if assigned(p) and (hp3.typ = ait_align) then
  7352. GetNextInstruction(p, p);
  7353. { Don't dereference yet, as doing so will cause
  7354. GetNextInstruction to skip the label and
  7355. optional align marker. [Kit] }
  7356. GetNextInstruction(hp2, hp4);
  7357. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  7358. { remove jCC }
  7359. RemoveInstruction(hp1);
  7360. { Now we can safely decrement it }
  7361. tasmlabel(symbol).decrefs;
  7362. { Remove label xxx (it will have a ref of zero due to the initial check }
  7363. StripLabelFast(hp4);
  7364. { remove jmp }
  7365. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  7366. RemoveInstruction(hp2);
  7367. { As before, now we can safely decrement it }
  7368. tasmlabel(symbol).decrefs;
  7369. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  7370. if tasmlabel(symbol).getrefs = 0 then
  7371. StripLabelFast(hp3);
  7372. if Assigned(p) then
  7373. begin
  7374. UpdateUsedRegs(p);
  7375. result:=true;
  7376. end;
  7377. exit;
  7378. end;
  7379. end;
  7380. end;
  7381. end;
  7382. {$endif i8086}
  7383. end;
  7384. end;
  7385. end;
  7386. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  7387. var
  7388. hp1,hp2: tai;
  7389. reg_and_hp1_is_instr: Boolean;
  7390. begin
  7391. result:=false;
  7392. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  7393. GetNextInstruction(p,hp1) and
  7394. (hp1.typ = ait_instruction);
  7395. if reg_and_hp1_is_instr and
  7396. (
  7397. (taicpu(hp1).opcode <> A_LEA) or
  7398. { If the LEA instruction can be converted into an arithmetic instruction,
  7399. it may be possible to then fold it. }
  7400. (
  7401. { If the flags register is in use, don't change the instruction
  7402. to an ADD otherwise this will scramble the flags. [Kit] }
  7403. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  7404. ConvertLEA(taicpu(hp1))
  7405. )
  7406. ) and
  7407. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  7408. GetNextInstruction(hp1,hp2) and
  7409. MatchInstruction(hp2,A_MOV,[]) and
  7410. (taicpu(hp2).oper[0]^.typ = top_reg) and
  7411. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  7412. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  7413. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  7414. {$ifdef i386}
  7415. { not all registers have byte size sub registers on i386 }
  7416. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  7417. {$endif i386}
  7418. (((taicpu(hp1).ops=2) and
  7419. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7420. ((taicpu(hp1).ops=1) and
  7421. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  7422. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  7423. begin
  7424. { change movsX/movzX reg/ref, reg2
  7425. add/sub/or/... reg3/$const, reg2
  7426. mov reg2 reg/ref
  7427. to add/sub/or/... reg3/$const, reg/ref }
  7428. { by example:
  7429. movswl %si,%eax movswl %si,%eax p
  7430. decl %eax addl %edx,%eax hp1
  7431. movw %ax,%si movw %ax,%si hp2
  7432. ->
  7433. movswl %si,%eax movswl %si,%eax p
  7434. decw %eax addw %edx,%eax hp1
  7435. movw %ax,%si movw %ax,%si hp2
  7436. }
  7437. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  7438. {
  7439. ->
  7440. movswl %si,%eax movswl %si,%eax p
  7441. decw %si addw %dx,%si hp1
  7442. movw %ax,%si movw %ax,%si hp2
  7443. }
  7444. case taicpu(hp1).ops of
  7445. 1:
  7446. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  7447. 2:
  7448. begin
  7449. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  7450. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7451. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  7452. end;
  7453. else
  7454. internalerror(2008042702);
  7455. end;
  7456. {
  7457. ->
  7458. decw %si addw %dx,%si p
  7459. }
  7460. DebugMsg(SPeepholeOptimization + 'var3',p);
  7461. RemoveCurrentP(p, hp1);
  7462. RemoveInstruction(hp2);
  7463. end
  7464. else if reg_and_hp1_is_instr and
  7465. (taicpu(hp1).opcode = A_MOV) and
  7466. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7467. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  7468. {$ifdef x86_64}
  7469. { check for implicit extension to 64 bit }
  7470. or
  7471. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7472. (taicpu(hp1).opsize=S_Q) and
  7473. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  7474. )
  7475. {$endif x86_64}
  7476. )
  7477. then
  7478. begin
  7479. { change
  7480. movx %reg1,%reg2
  7481. mov %reg2,%reg3
  7482. dealloc %reg2
  7483. into
  7484. movx %reg,%reg3
  7485. }
  7486. TransferUsedRegs(TmpUsedRegs);
  7487. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7488. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7489. begin
  7490. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  7491. {$ifdef x86_64}
  7492. if (taicpu(p).opsize in [S_BL,S_WL]) and
  7493. (taicpu(hp1).opsize=S_Q) then
  7494. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  7495. else
  7496. {$endif x86_64}
  7497. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7498. RemoveInstruction(hp1);
  7499. end;
  7500. end
  7501. else if reg_and_hp1_is_instr and
  7502. (taicpu(hp1).opcode = A_MOV) and
  7503. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7504. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  7505. (taicpu(hp1).opsize=S_B)) or
  7506. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  7507. (taicpu(hp1).opsize=S_W))
  7508. {$ifdef x86_64}
  7509. or ((taicpu(p).opsize=S_LQ) and
  7510. (taicpu(hp1).opsize=S_L))
  7511. {$endif x86_64}
  7512. ) and
  7513. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  7514. begin
  7515. { change
  7516. movx %reg1,%reg2
  7517. mov %reg2,%reg3
  7518. dealloc %reg2
  7519. into
  7520. mov %reg1,%reg3
  7521. if the second mov accesses only the bits stored in reg1
  7522. }
  7523. TransferUsedRegs(TmpUsedRegs);
  7524. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7525. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7526. begin
  7527. DebugMsg(SPeepholeOptimization + 'MovxMov2Mov',p);
  7528. if taicpu(p).oper[0]^.typ=top_reg then
  7529. begin
  7530. case taicpu(hp1).opsize of
  7531. S_B:
  7532. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  7533. S_W:
  7534. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  7535. S_L:
  7536. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  7537. else
  7538. Internalerror(2020102301);
  7539. end;
  7540. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  7541. end
  7542. else
  7543. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  7544. RemoveCurrentP(p);
  7545. result:=true;
  7546. exit;
  7547. end;
  7548. end
  7549. else if reg_and_hp1_is_instr and
  7550. (taicpu(p).oper[0]^.typ = top_reg) and
  7551. (
  7552. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  7553. ) and
  7554. (taicpu(hp1).oper[0]^.typ = top_const) and
  7555. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7556. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7557. { Minimum shift value allowed is the bit difference between the sizes }
  7558. (taicpu(hp1).oper[0]^.val >=
  7559. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7560. 8 * (
  7561. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  7562. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7563. )
  7564. ) then
  7565. begin
  7566. { For:
  7567. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  7568. shl/sal ##, %reg1
  7569. Remove the movsx/movzx instruction if the shift overwrites the
  7570. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  7571. }
  7572. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  7573. RemoveCurrentP(p, hp1);
  7574. Result := True;
  7575. Exit;
  7576. end
  7577. else if reg_and_hp1_is_instr and
  7578. (taicpu(p).oper[0]^.typ = top_reg) and
  7579. (
  7580. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  7581. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  7582. ) and
  7583. (taicpu(hp1).oper[0]^.typ = top_const) and
  7584. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7585. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7586. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  7587. (taicpu(hp1).oper[0]^.val <
  7588. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7589. 8 * (
  7590. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7591. )
  7592. ) then
  7593. begin
  7594. { For:
  7595. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  7596. sar ##, %reg1 shr ##, %reg1
  7597. Move the shift to before the movx instruction if the shift value
  7598. is not too large.
  7599. }
  7600. asml.Remove(hp1);
  7601. asml.InsertBefore(hp1, p);
  7602. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  7603. case taicpu(p).opsize of
  7604. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  7605. taicpu(hp1).opsize := S_B;
  7606. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  7607. taicpu(hp1).opsize := S_W;
  7608. {$ifdef x86_64}
  7609. S_LQ:
  7610. taicpu(hp1).opsize := S_L;
  7611. {$endif}
  7612. else
  7613. InternalError(2020112401);
  7614. end;
  7615. if (taicpu(hp1).opcode = A_SHR) then
  7616. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  7617. else
  7618. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  7619. Result := True;
  7620. end
  7621. else if taicpu(p).opcode=A_MOVZX then
  7622. begin
  7623. { removes superfluous And's after movzx's }
  7624. if reg_and_hp1_is_instr and
  7625. (taicpu(hp1).opcode = A_AND) and
  7626. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7627. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  7628. {$ifdef x86_64}
  7629. { check for implicit extension to 64 bit }
  7630. or
  7631. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7632. (taicpu(hp1).opsize=S_Q) and
  7633. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  7634. )
  7635. {$endif x86_64}
  7636. )
  7637. then
  7638. begin
  7639. case taicpu(p).opsize Of
  7640. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7641. if (taicpu(hp1).oper[0]^.val = $ff) then
  7642. begin
  7643. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  7644. RemoveInstruction(hp1);
  7645. Result:=true;
  7646. exit;
  7647. end;
  7648. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7649. if (taicpu(hp1).oper[0]^.val = $ffff) then
  7650. begin
  7651. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  7652. RemoveInstruction(hp1);
  7653. Result:=true;
  7654. exit;
  7655. end;
  7656. {$ifdef x86_64}
  7657. S_LQ:
  7658. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  7659. begin
  7660. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  7661. RemoveInstruction(hp1);
  7662. Result:=true;
  7663. exit;
  7664. end;
  7665. {$endif x86_64}
  7666. else
  7667. ;
  7668. end;
  7669. { we cannot get rid of the and, but can we get rid of the movz ?}
  7670. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  7671. begin
  7672. case taicpu(p).opsize Of
  7673. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7674. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  7675. begin
  7676. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  7677. RemoveCurrentP(p,hp1);
  7678. Result:=true;
  7679. exit;
  7680. end;
  7681. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7682. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  7683. begin
  7684. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  7685. RemoveCurrentP(p,hp1);
  7686. Result:=true;
  7687. exit;
  7688. end;
  7689. {$ifdef x86_64}
  7690. S_LQ:
  7691. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  7692. begin
  7693. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  7694. RemoveCurrentP(p,hp1);
  7695. Result:=true;
  7696. exit;
  7697. end;
  7698. {$endif x86_64}
  7699. else
  7700. ;
  7701. end;
  7702. end;
  7703. end;
  7704. { changes some movzx constructs to faster synonyms (all examples
  7705. are given with eax/ax, but are also valid for other registers)}
  7706. if MatchOpType(taicpu(p),top_reg,top_reg) then
  7707. begin
  7708. case taicpu(p).opsize of
  7709. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  7710. (the machine code is equivalent to movzbl %al,%eax), but the
  7711. code generator still generates that assembler instruction and
  7712. it is silently converted. This should probably be checked.
  7713. [Kit] }
  7714. S_BW:
  7715. begin
  7716. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7717. (
  7718. not IsMOVZXAcceptable
  7719. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  7720. or (
  7721. (cs_opt_size in current_settings.optimizerswitches) and
  7722. (taicpu(p).oper[1]^.reg = NR_AX)
  7723. )
  7724. ) then
  7725. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  7726. begin
  7727. DebugMsg(SPeepholeOptimization + 'var7',p);
  7728. taicpu(p).opcode := A_AND;
  7729. taicpu(p).changeopsize(S_W);
  7730. taicpu(p).loadConst(0,$ff);
  7731. Result := True;
  7732. end
  7733. else if not IsMOVZXAcceptable and
  7734. GetNextInstruction(p, hp1) and
  7735. (tai(hp1).typ = ait_instruction) and
  7736. (taicpu(hp1).opcode = A_AND) and
  7737. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7738. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7739. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  7740. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  7741. begin
  7742. DebugMsg(SPeepholeOptimization + 'var8',p);
  7743. taicpu(p).opcode := A_MOV;
  7744. taicpu(p).changeopsize(S_W);
  7745. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  7746. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7747. Result := True;
  7748. end;
  7749. end;
  7750. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  7751. S_BL:
  7752. begin
  7753. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7754. (
  7755. not IsMOVZXAcceptable
  7756. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  7757. or (
  7758. (cs_opt_size in current_settings.optimizerswitches) and
  7759. (taicpu(p).oper[1]^.reg = NR_EAX)
  7760. )
  7761. ) then
  7762. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  7763. begin
  7764. DebugMsg(SPeepholeOptimization + 'var9',p);
  7765. taicpu(p).opcode := A_AND;
  7766. taicpu(p).changeopsize(S_L);
  7767. taicpu(p).loadConst(0,$ff);
  7768. Result := True;
  7769. end
  7770. else if not IsMOVZXAcceptable and
  7771. GetNextInstruction(p, hp1) and
  7772. (tai(hp1).typ = ait_instruction) and
  7773. (taicpu(hp1).opcode = A_AND) and
  7774. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7775. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7776. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  7777. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  7778. begin
  7779. DebugMsg(SPeepholeOptimization + 'var10',p);
  7780. taicpu(p).opcode := A_MOV;
  7781. taicpu(p).changeopsize(S_L);
  7782. { do not use R_SUBWHOLE
  7783. as movl %rdx,%eax
  7784. is invalid in assembler PM }
  7785. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  7786. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7787. Result := True;
  7788. end;
  7789. end;
  7790. {$endif i8086}
  7791. S_WL:
  7792. if not IsMOVZXAcceptable then
  7793. begin
  7794. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  7795. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  7796. begin
  7797. DebugMsg(SPeepholeOptimization + 'var11',p);
  7798. taicpu(p).opcode := A_AND;
  7799. taicpu(p).changeopsize(S_L);
  7800. taicpu(p).loadConst(0,$ffff);
  7801. Result := True;
  7802. end
  7803. else if GetNextInstruction(p, hp1) and
  7804. (tai(hp1).typ = ait_instruction) and
  7805. (taicpu(hp1).opcode = A_AND) and
  7806. (taicpu(hp1).oper[0]^.typ = top_const) and
  7807. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7808. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7809. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  7810. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  7811. begin
  7812. DebugMsg(SPeepholeOptimization + 'var12',p);
  7813. taicpu(p).opcode := A_MOV;
  7814. taicpu(p).changeopsize(S_L);
  7815. { do not use R_SUBWHOLE
  7816. as movl %rdx,%eax
  7817. is invalid in assembler PM }
  7818. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  7819. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  7820. Result := True;
  7821. end;
  7822. end;
  7823. else
  7824. InternalError(2017050705);
  7825. end;
  7826. end
  7827. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  7828. begin
  7829. if GetNextInstruction(p, hp1) and
  7830. (tai(hp1).typ = ait_instruction) and
  7831. (taicpu(hp1).opcode = A_AND) and
  7832. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7833. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7834. begin
  7835. //taicpu(p).opcode := A_MOV;
  7836. case taicpu(p).opsize Of
  7837. S_BL:
  7838. begin
  7839. DebugMsg(SPeepholeOptimization + 'var13',p);
  7840. taicpu(hp1).changeopsize(S_L);
  7841. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7842. end;
  7843. S_WL:
  7844. begin
  7845. DebugMsg(SPeepholeOptimization + 'var14',p);
  7846. taicpu(hp1).changeopsize(S_L);
  7847. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  7848. end;
  7849. S_BW:
  7850. begin
  7851. DebugMsg(SPeepholeOptimization + 'var15',p);
  7852. taicpu(hp1).changeopsize(S_W);
  7853. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7854. end;
  7855. else
  7856. Internalerror(2017050704)
  7857. end;
  7858. Result := True;
  7859. end;
  7860. end;
  7861. end;
  7862. end;
  7863. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  7864. var
  7865. hp1, hp2 : tai;
  7866. MaskLength : Cardinal;
  7867. MaskedBits : TCgInt;
  7868. begin
  7869. Result:=false;
  7870. { There are no optimisations for reference targets }
  7871. if (taicpu(p).oper[1]^.typ <> top_reg) then
  7872. Exit;
  7873. while GetNextInstruction(p, hp1) and
  7874. (hp1.typ = ait_instruction) do
  7875. begin
  7876. if (taicpu(p).oper[0]^.typ = top_const) then
  7877. begin
  7878. if (taicpu(hp1).opcode = A_AND) and
  7879. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7880. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7881. { the second register must contain the first one, so compare their subreg types }
  7882. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  7883. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  7884. { change
  7885. and const1, reg
  7886. and const2, reg
  7887. to
  7888. and (const1 and const2), reg
  7889. }
  7890. begin
  7891. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  7892. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  7893. RemoveCurrentP(p, hp1);
  7894. Result:=true;
  7895. exit;
  7896. end
  7897. else if (taicpu(hp1).opcode = A_MOVZX) and
  7898. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7899. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  7900. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7901. (((taicpu(p).opsize=S_W) and
  7902. (taicpu(hp1).opsize=S_BW)) or
  7903. ((taicpu(p).opsize=S_L) and
  7904. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}]))
  7905. {$ifdef x86_64}
  7906. or
  7907. ((taicpu(p).opsize=S_Q) and
  7908. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL]))
  7909. {$endif x86_64}
  7910. ) then
  7911. begin
  7912. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  7913. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  7914. ) or
  7915. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  7916. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  7917. then
  7918. begin
  7919. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  7920. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  7921. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  7922. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  7923. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  7924. }
  7925. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  7926. RemoveInstruction(hp1);
  7927. { See if there are other optimisations possible }
  7928. Continue;
  7929. end;
  7930. end
  7931. else if (taicpu(hp1).opcode = A_SHL) and
  7932. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7933. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7934. begin
  7935. {$ifopt R+}
  7936. {$define RANGE_WAS_ON}
  7937. {$R-}
  7938. {$endif}
  7939. { get length of potential and mask }
  7940. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  7941. { really a mask? }
  7942. {$ifdef RANGE_WAS_ON}
  7943. {$R+}
  7944. {$endif}
  7945. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  7946. { unmasked part shifted out? }
  7947. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  7948. begin
  7949. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  7950. RemoveCurrentP(p, hp1);
  7951. Result:=true;
  7952. exit;
  7953. end;
  7954. end
  7955. else if (taicpu(hp1).opcode = A_SHR) and
  7956. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7957. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  7958. (taicpu(hp1).oper[0]^.val <= 63) then
  7959. begin
  7960. { Does SHR combined with the AND cover all the bits?
  7961. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  7962. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  7963. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  7964. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  7965. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  7966. begin
  7967. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  7968. RemoveCurrentP(p, hp1);
  7969. Result := True;
  7970. Exit;
  7971. end;
  7972. end
  7973. else if ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}) and
  7974. (taicpu(hp1).oper[0]^.typ = top_reg) and
  7975. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  7976. begin
  7977. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  7978. (
  7979. (
  7980. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  7981. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  7982. ) or (
  7983. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  7984. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  7985. {$ifdef x86_64}
  7986. ) or (
  7987. (taicpu(hp1).opsize = S_LQ) and
  7988. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  7989. {$endif x86_64}
  7990. )
  7991. ) then
  7992. begin
  7993. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  7994. begin
  7995. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  7996. RemoveInstruction(hp1);
  7997. { See if there are other optimisations possible }
  7998. Continue;
  7999. end;
  8000. { The super-registers are the same though.
  8001. Note that this change by itself doesn't improve
  8002. code speed, but it opens up other optimisations. }
  8003. {$ifdef x86_64}
  8004. { Convert 64-bit register to 32-bit }
  8005. case taicpu(hp1).opsize of
  8006. S_BQ:
  8007. begin
  8008. taicpu(hp1).opsize := S_BL;
  8009. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8010. end;
  8011. S_WQ:
  8012. begin
  8013. taicpu(hp1).opsize := S_WL;
  8014. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8015. end
  8016. else
  8017. ;
  8018. end;
  8019. {$endif x86_64}
  8020. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  8021. taicpu(hp1).opcode := A_MOVZX;
  8022. { See if there are other optimisations possible }
  8023. Continue;
  8024. end;
  8025. end;
  8026. end;
  8027. if (taicpu(hp1).is_jmp) and
  8028. (taicpu(hp1).opcode<>A_JMP) and
  8029. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  8030. begin
  8031. { change
  8032. and x, reg
  8033. jxx
  8034. to
  8035. test x, reg
  8036. jxx
  8037. if reg is deallocated before the
  8038. jump, but only if it's a conditional jump (PFV)
  8039. }
  8040. taicpu(p).opcode := A_TEST;
  8041. Exit;
  8042. end;
  8043. Break;
  8044. end;
  8045. { Lone AND tests }
  8046. if (taicpu(p).oper[0]^.typ = top_const) then
  8047. begin
  8048. {
  8049. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  8050. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  8051. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  8052. }
  8053. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  8054. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  8055. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  8056. begin
  8057. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  8058. if taicpu(p).opsize = S_L then
  8059. begin
  8060. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  8061. Result := True;
  8062. end;
  8063. end;
  8064. end;
  8065. { Backward check to determine necessity of and %reg,%reg }
  8066. if (taicpu(p).oper[0]^.typ = top_reg) and
  8067. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  8068. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  8069. GetLastInstruction(p, hp2) and
  8070. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  8071. { Check size of adjacent instruction to determine if the AND is
  8072. effectively a null operation }
  8073. (
  8074. (taicpu(p).opsize = taicpu(hp2).opsize) or
  8075. { Note: Don't include S_Q }
  8076. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  8077. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  8078. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  8079. ) then
  8080. begin
  8081. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  8082. { If GetNextInstruction returned False, hp1 will be nil }
  8083. RemoveCurrentP(p, hp1);
  8084. Result := True;
  8085. Exit;
  8086. end;
  8087. end;
  8088. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  8089. var
  8090. hp1: tai; NewRef: TReference;
  8091. { This entire nested function is used in an if-statement below, but we
  8092. want to avoid all the used reg transfers and GetNextInstruction calls
  8093. until we really have to check }
  8094. function MemRegisterNotUsedLater: Boolean; inline;
  8095. var
  8096. hp2: tai;
  8097. begin
  8098. TransferUsedRegs(TmpUsedRegs);
  8099. hp2 := p;
  8100. repeat
  8101. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8102. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8103. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  8104. end;
  8105. begin
  8106. Result := False;
  8107. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  8108. Exit;
  8109. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  8110. begin
  8111. { Change:
  8112. add %reg2,%reg1
  8113. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  8114. To:
  8115. mov/s/z #(%reg1,%reg2),%reg1
  8116. }
  8117. if MatchOpType(taicpu(p), top_reg, top_reg) and
  8118. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  8119. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  8120. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  8121. (
  8122. (
  8123. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  8124. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  8125. { r/esp cannot be an index }
  8126. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  8127. ) or (
  8128. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  8129. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  8130. )
  8131. ) and (
  8132. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  8133. (
  8134. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  8135. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8136. MemRegisterNotUsedLater
  8137. )
  8138. ) then
  8139. begin
  8140. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  8141. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  8142. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  8143. RemoveCurrentp(p, hp1);
  8144. Result := True;
  8145. Exit;
  8146. end;
  8147. { Change:
  8148. addl/q $x,%reg1
  8149. movl/q %reg1,%reg2
  8150. To:
  8151. leal/q $x(%reg1),%reg2
  8152. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8153. Breaks the dependency chain.
  8154. }
  8155. if MatchOpType(taicpu(p),top_const,top_reg) and
  8156. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8157. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8158. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8159. (
  8160. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  8161. not (cs_opt_size in current_settings.optimizerswitches) or
  8162. (
  8163. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8164. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8165. )
  8166. ) then
  8167. begin
  8168. { Change the MOV instruction to a LEA instruction, and update the
  8169. first operand }
  8170. reference_reset(NewRef, 1, []);
  8171. NewRef.base := taicpu(p).oper[1]^.reg;
  8172. NewRef.scalefactor := 1;
  8173. NewRef.offset := taicpu(p).oper[0]^.val;
  8174. taicpu(hp1).opcode := A_LEA;
  8175. taicpu(hp1).loadref(0, NewRef);
  8176. TransferUsedRegs(TmpUsedRegs);
  8177. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8178. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8179. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8180. begin
  8181. { Move what is now the LEA instruction to before the SUB instruction }
  8182. Asml.Remove(hp1);
  8183. Asml.InsertBefore(hp1, p);
  8184. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8185. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  8186. p := hp1;
  8187. end
  8188. else
  8189. begin
  8190. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8191. RemoveCurrentP(p, hp1);
  8192. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  8193. end;
  8194. Result := True;
  8195. end;
  8196. end;
  8197. end;
  8198. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  8199. begin
  8200. Result:=false;
  8201. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8202. begin
  8203. if MatchReference(taicpu(p).oper[0]^.ref^,taicpu(p).oper[1]^.reg,NR_INVALID) and
  8204. (taicpu(p).oper[0]^.ref^.index<>NR_NO) then
  8205. begin
  8206. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.base);
  8207. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.index);
  8208. taicpu(p).opcode:=A_ADD;
  8209. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  8210. result:=true;
  8211. end
  8212. else if MatchReference(taicpu(p).oper[0]^.ref^,NR_INVALID,taicpu(p).oper[1]^.reg) and
  8213. (taicpu(p).oper[0]^.ref^.base<>NR_NO) then
  8214. begin
  8215. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.index);
  8216. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.base);
  8217. taicpu(p).opcode:=A_ADD;
  8218. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  8219. result:=true;
  8220. end;
  8221. end;
  8222. end;
  8223. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  8224. var
  8225. hp1: tai; NewRef: TReference;
  8226. begin
  8227. { Change:
  8228. subl/q $x,%reg1
  8229. movl/q %reg1,%reg2
  8230. To:
  8231. leal/q $-x(%reg1),%reg2
  8232. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8233. Breaks the dependency chain and potentially permits the removal of
  8234. a CMP instruction if one follows.
  8235. }
  8236. Result := False;
  8237. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8238. MatchOpType(taicpu(p),top_const,top_reg) and
  8239. GetNextInstruction(p, hp1) and
  8240. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8241. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8242. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8243. (
  8244. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  8245. not (cs_opt_size in current_settings.optimizerswitches) or
  8246. (
  8247. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8248. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8249. )
  8250. ) then
  8251. begin
  8252. { Change the MOV instruction to a LEA instruction, and update the
  8253. first operand }
  8254. reference_reset(NewRef, 1, []);
  8255. NewRef.base := taicpu(p).oper[1]^.reg;
  8256. NewRef.scalefactor := 1;
  8257. NewRef.offset := -taicpu(p).oper[0]^.val;
  8258. taicpu(hp1).opcode := A_LEA;
  8259. taicpu(hp1).loadref(0, NewRef);
  8260. TransferUsedRegs(TmpUsedRegs);
  8261. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8262. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8263. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8264. begin
  8265. { Move what is now the LEA instruction to before the SUB instruction }
  8266. Asml.Remove(hp1);
  8267. Asml.InsertBefore(hp1, p);
  8268. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8269. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  8270. p := hp1;
  8271. end
  8272. else
  8273. begin
  8274. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8275. RemoveCurrentP(p, hp1);
  8276. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  8277. end;
  8278. Result := True;
  8279. end;
  8280. end;
  8281. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  8282. begin
  8283. { we can skip all instructions not messing with the stack pointer }
  8284. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  8285. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  8286. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  8287. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  8288. ({(taicpu(hp1).ops=0) or }
  8289. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  8290. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  8291. ) and }
  8292. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  8293. )
  8294. ) do
  8295. GetNextInstruction(hp1,hp1);
  8296. Result:=assigned(hp1);
  8297. end;
  8298. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  8299. var
  8300. hp1, hp2, hp3, hp4, hp5: tai;
  8301. begin
  8302. Result:=false;
  8303. hp5:=nil;
  8304. { replace
  8305. leal(q) x(<stackpointer>),<stackpointer>
  8306. call procname
  8307. leal(q) -x(<stackpointer>),<stackpointer>
  8308. ret
  8309. by
  8310. jmp procname
  8311. but do it only on level 4 because it destroys stack back traces
  8312. }
  8313. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8314. MatchOpType(taicpu(p),top_ref,top_reg) and
  8315. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8316. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  8317. { the -8 or -24 are not required, but bail out early if possible,
  8318. higher values are unlikely }
  8319. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  8320. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  8321. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  8322. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  8323. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  8324. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8325. GetNextInstruction(p, hp1) and
  8326. { Take a copy of hp1 }
  8327. SetAndTest(hp1, hp4) and
  8328. { trick to skip label }
  8329. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8330. SkipSimpleInstructions(hp1) and
  8331. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8332. GetNextInstruction(hp1, hp2) and
  8333. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  8334. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  8335. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  8336. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8337. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  8338. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  8339. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  8340. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  8341. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8342. GetNextInstruction(hp2, hp3) and
  8343. { trick to skip label }
  8344. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8345. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8346. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8347. SetAndTest(hp3,hp5) and
  8348. GetNextInstruction(hp3,hp3) and
  8349. MatchInstruction(hp3,A_RET,[S_NO])
  8350. )
  8351. ) and
  8352. (taicpu(hp3).ops=0) then
  8353. begin
  8354. taicpu(hp1).opcode := A_JMP;
  8355. taicpu(hp1).is_jmp := true;
  8356. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  8357. RemoveCurrentP(p, hp4);
  8358. RemoveInstruction(hp2);
  8359. RemoveInstruction(hp3);
  8360. if Assigned(hp5) then
  8361. begin
  8362. AsmL.Remove(hp5);
  8363. ASmL.InsertBefore(hp5,hp1)
  8364. end;
  8365. Result:=true;
  8366. end;
  8367. end;
  8368. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  8369. {$ifdef x86_64}
  8370. var
  8371. hp1, hp2, hp3, hp4, hp5: tai;
  8372. {$endif x86_64}
  8373. begin
  8374. Result:=false;
  8375. {$ifdef x86_64}
  8376. hp5:=nil;
  8377. { replace
  8378. push %rax
  8379. call procname
  8380. pop %rcx
  8381. ret
  8382. by
  8383. jmp procname
  8384. but do it only on level 4 because it destroys stack back traces
  8385. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  8386. for all supported calling conventions
  8387. }
  8388. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8389. MatchOpType(taicpu(p),top_reg) and
  8390. (taicpu(p).oper[0]^.reg=NR_RAX) and
  8391. GetNextInstruction(p, hp1) and
  8392. { Take a copy of hp1 }
  8393. SetAndTest(hp1, hp4) and
  8394. { trick to skip label }
  8395. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8396. SkipSimpleInstructions(hp1) and
  8397. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8398. GetNextInstruction(hp1, hp2) and
  8399. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  8400. MatchOpType(taicpu(hp2),top_reg) and
  8401. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  8402. GetNextInstruction(hp2, hp3) and
  8403. { trick to skip label }
  8404. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8405. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8406. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8407. SetAndTest(hp3,hp5) and
  8408. GetNextInstruction(hp3,hp3) and
  8409. MatchInstruction(hp3,A_RET,[S_NO])
  8410. )
  8411. ) and
  8412. (taicpu(hp3).ops=0) then
  8413. begin
  8414. taicpu(hp1).opcode := A_JMP;
  8415. taicpu(hp1).is_jmp := true;
  8416. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  8417. RemoveCurrentP(p, hp4);
  8418. RemoveInstruction(hp2);
  8419. RemoveInstruction(hp3);
  8420. if Assigned(hp5) then
  8421. begin
  8422. AsmL.Remove(hp5);
  8423. ASmL.InsertBefore(hp5,hp1)
  8424. end;
  8425. Result:=true;
  8426. end;
  8427. {$endif x86_64}
  8428. end;
  8429. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  8430. var
  8431. Value, RegName: string;
  8432. begin
  8433. Result:=false;
  8434. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  8435. begin
  8436. case taicpu(p).oper[0]^.val of
  8437. 0:
  8438. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  8439. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8440. begin
  8441. { change "mov $0,%reg" into "xor %reg,%reg" }
  8442. taicpu(p).opcode := A_XOR;
  8443. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  8444. Result := True;
  8445. end;
  8446. $1..$FFFFFFFF:
  8447. begin
  8448. { Code size reduction by J. Gareth "Kit" Moreton }
  8449. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  8450. case taicpu(p).opsize of
  8451. S_Q:
  8452. begin
  8453. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  8454. Value := debug_tostr(taicpu(p).oper[0]^.val);
  8455. { The actual optimization }
  8456. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8457. taicpu(p).changeopsize(S_L);
  8458. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  8459. Result := True;
  8460. end;
  8461. else
  8462. { Do nothing };
  8463. end;
  8464. end;
  8465. -1:
  8466. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  8467. if (cs_opt_size in current_settings.optimizerswitches) and
  8468. (taicpu(p).opsize <> S_B) and
  8469. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8470. begin
  8471. { change "mov $-1,%reg" into "or $-1,%reg" }
  8472. { NOTES:
  8473. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  8474. - This operation creates a false dependency on the register, so only do it when optimising for size
  8475. - 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
  8476. }
  8477. taicpu(p).opcode := A_OR;
  8478. Result := True;
  8479. end;
  8480. end;
  8481. end;
  8482. end;
  8483. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  8484. var
  8485. hp1: tai;
  8486. begin
  8487. { Detect:
  8488. andw x, %ax (0 <= x < $8000)
  8489. ...
  8490. movzwl %ax,%eax
  8491. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8492. }
  8493. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  8494. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8495. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  8496. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8497. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8498. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8499. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8500. begin
  8501. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  8502. taicpu(hp1).opcode := A_CWDE;
  8503. taicpu(hp1).clearop(0);
  8504. taicpu(hp1).clearop(1);
  8505. taicpu(hp1).ops := 0;
  8506. { A change was made, but not with p, so move forward 1 }
  8507. p := tai(p.Next);
  8508. Result := True;
  8509. end;
  8510. end;
  8511. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  8512. begin
  8513. Result := False;
  8514. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  8515. Exit;
  8516. { Convert:
  8517. movswl %ax,%eax -> cwtl
  8518. movslq %eax,%rax -> cdqe
  8519. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  8520. refer to the same opcode and depends only on the assembler's
  8521. current operand-size attribute. [Kit]
  8522. }
  8523. with taicpu(p) do
  8524. case opsize of
  8525. S_WL:
  8526. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  8527. begin
  8528. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  8529. opcode := A_CWDE;
  8530. clearop(0);
  8531. clearop(1);
  8532. ops := 0;
  8533. Result := True;
  8534. end;
  8535. {$ifdef x86_64}
  8536. S_LQ:
  8537. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  8538. begin
  8539. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  8540. opcode := A_CDQE;
  8541. clearop(0);
  8542. clearop(1);
  8543. ops := 0;
  8544. Result := True;
  8545. end;
  8546. {$endif x86_64}
  8547. else
  8548. ;
  8549. end;
  8550. end;
  8551. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  8552. var
  8553. hp1: tai;
  8554. begin
  8555. { Detect:
  8556. shr x, %ax (x > 0)
  8557. ...
  8558. movzwl %ax,%eax
  8559. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8560. }
  8561. Result := False;
  8562. if MatchOpType(taicpu(p), top_const, top_reg) and
  8563. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8564. (taicpu(p).oper[0]^.val > 0) and
  8565. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8566. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8567. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8568. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8569. begin
  8570. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  8571. taicpu(hp1).opcode := A_CWDE;
  8572. taicpu(hp1).clearop(0);
  8573. taicpu(hp1).clearop(1);
  8574. taicpu(hp1).ops := 0;
  8575. { A change was made, but not with p, so move forward 1 }
  8576. p := tai(p.Next);
  8577. Result := True;
  8578. end;
  8579. end;
  8580. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  8581. begin
  8582. Result:=false;
  8583. { change "cmp $0, %reg" to "test %reg, %reg" }
  8584. if MatchOpType(taicpu(p),top_const,top_reg) and
  8585. (taicpu(p).oper[0]^.val = 0) then
  8586. begin
  8587. taicpu(p).opcode := A_TEST;
  8588. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8589. Result:=true;
  8590. end;
  8591. end;
  8592. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  8593. var
  8594. IsTestConstX : Boolean;
  8595. hp1,hp2 : tai;
  8596. begin
  8597. Result:=false;
  8598. { removes the line marked with (x) from the sequence
  8599. and/or/xor/add/sub/... $x, %y
  8600. test/or %y, %y | test $-1, %y (x)
  8601. j(n)z _Label
  8602. as the first instruction already adjusts the ZF
  8603. %y operand may also be a reference }
  8604. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  8605. MatchOperand(taicpu(p).oper[0]^,-1);
  8606. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  8607. GetLastInstruction(p, hp1) and
  8608. (tai(hp1).typ = ait_instruction) and
  8609. GetNextInstruction(p,hp2) and
  8610. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  8611. case taicpu(hp1).opcode Of
  8612. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  8613. begin
  8614. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  8615. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8616. { and in case of carry for A(E)/B(E)/C/NC }
  8617. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  8618. ((taicpu(hp1).opcode <> A_ADD) and
  8619. (taicpu(hp1).opcode <> A_SUB))) then
  8620. begin
  8621. RemoveCurrentP(p, hp2);
  8622. Result:=true;
  8623. Exit;
  8624. end;
  8625. end;
  8626. A_SHL, A_SAL, A_SHR, A_SAR:
  8627. begin
  8628. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  8629. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  8630. { therefore, it's only safe to do this optimization for }
  8631. { shifts by a (nonzero) constant }
  8632. (taicpu(hp1).oper[0]^.typ = top_const) and
  8633. (taicpu(hp1).oper[0]^.val <> 0) and
  8634. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8635. { and in case of carry for A(E)/B(E)/C/NC }
  8636. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  8637. begin
  8638. RemoveCurrentP(p, hp2);
  8639. Result:=true;
  8640. Exit;
  8641. end;
  8642. end;
  8643. A_DEC, A_INC, A_NEG:
  8644. begin
  8645. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  8646. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8647. { and in case of carry for A(E)/B(E)/C/NC }
  8648. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  8649. begin
  8650. case taicpu(hp1).opcode of
  8651. A_DEC, A_INC:
  8652. { replace inc/dec with add/sub 1, because inc/dec doesn't set the carry flag }
  8653. begin
  8654. case taicpu(hp1).opcode Of
  8655. A_DEC: taicpu(hp1).opcode := A_SUB;
  8656. A_INC: taicpu(hp1).opcode := A_ADD;
  8657. else
  8658. ;
  8659. end;
  8660. taicpu(hp1).loadoper(1,taicpu(hp1).oper[0]^);
  8661. taicpu(hp1).loadConst(0,1);
  8662. taicpu(hp1).ops:=2;
  8663. end;
  8664. else
  8665. ;
  8666. end;
  8667. RemoveCurrentP(p, hp2);
  8668. Result:=true;
  8669. Exit;
  8670. end;
  8671. end
  8672. else
  8673. ;
  8674. end; { case }
  8675. { change "test $-1,%reg" into "test %reg,%reg" }
  8676. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  8677. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  8678. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  8679. if MatchInstruction(p, A_OR, []) and
  8680. { Can only match if they're both registers }
  8681. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  8682. begin
  8683. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  8684. taicpu(p).opcode := A_TEST;
  8685. { No need to set Result to True, as we've done all the optimisations we can }
  8686. end;
  8687. end;
  8688. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  8689. var
  8690. hp1,hp3 : tai;
  8691. {$ifndef x86_64}
  8692. hp2 : taicpu;
  8693. {$endif x86_64}
  8694. begin
  8695. Result:=false;
  8696. hp3:=nil;
  8697. {$ifndef x86_64}
  8698. { don't do this on modern CPUs, this really hurts them due to
  8699. broken call/ret pairing }
  8700. if (current_settings.optimizecputype < cpu_Pentium2) and
  8701. not(cs_create_pic in current_settings.moduleswitches) and
  8702. GetNextInstruction(p, hp1) and
  8703. MatchInstruction(hp1,A_JMP,[S_NO]) and
  8704. MatchOpType(taicpu(hp1),top_ref) and
  8705. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  8706. begin
  8707. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  8708. InsertLLItem(p.previous, p, hp2);
  8709. taicpu(p).opcode := A_JMP;
  8710. taicpu(p).is_jmp := true;
  8711. RemoveInstruction(hp1);
  8712. Result:=true;
  8713. end
  8714. else
  8715. {$endif x86_64}
  8716. { replace
  8717. call procname
  8718. ret
  8719. by
  8720. jmp procname
  8721. but do it only on level 4 because it destroys stack back traces
  8722. else if the subroutine is marked as no return, remove the ret
  8723. }
  8724. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  8725. (po_noreturn in current_procinfo.procdef.procoptions)) and
  8726. GetNextInstruction(p, hp1) and
  8727. (MatchInstruction(hp1,A_RET,[S_NO]) or
  8728. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  8729. SetAndTest(hp1,hp3) and
  8730. GetNextInstruction(hp1,hp1) and
  8731. MatchInstruction(hp1,A_RET,[S_NO])
  8732. )
  8733. ) and
  8734. (taicpu(hp1).ops=0) then
  8735. begin
  8736. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8737. { we might destroy stack alignment here if we do not do a call }
  8738. (target_info.stackalign<=sizeof(SizeUInt)) then
  8739. begin
  8740. taicpu(p).opcode := A_JMP;
  8741. taicpu(p).is_jmp := true;
  8742. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  8743. end
  8744. else
  8745. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  8746. RemoveInstruction(hp1);
  8747. if Assigned(hp3) then
  8748. begin
  8749. AsmL.Remove(hp3);
  8750. AsmL.InsertBefore(hp3,p)
  8751. end;
  8752. Result:=true;
  8753. end;
  8754. end;
  8755. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  8756. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  8757. begin
  8758. case OpSize of
  8759. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8760. Result := (Val <= $FF) and (Val >= -128);
  8761. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8762. Result := (Val <= $FFFF) and (Val >= -32768);
  8763. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  8764. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  8765. else
  8766. Result := True;
  8767. end;
  8768. end;
  8769. var
  8770. hp1, hp2 : tai;
  8771. SizeChange: Boolean;
  8772. PreMessage: string;
  8773. begin
  8774. Result := False;
  8775. if (taicpu(p).oper[0]^.typ = top_reg) and
  8776. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8777. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  8778. begin
  8779. { Change (using movzbl %al,%eax as an example):
  8780. movzbl %al, %eax movzbl %al, %eax
  8781. cmpl x, %eax testl %eax,%eax
  8782. To:
  8783. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  8784. movzbl %al, %eax movzbl %al, %eax
  8785. Smaller instruction and minimises pipeline stall as the CPU
  8786. doesn't have to wait for the register to get zero-extended. [Kit]
  8787. Also allow if the smaller of the two registers is being checked,
  8788. as this still removes the false dependency.
  8789. }
  8790. if
  8791. (
  8792. (
  8793. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  8794. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  8795. ) or (
  8796. { If MatchOperand returns True, they must both be registers }
  8797. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  8798. )
  8799. ) and
  8800. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  8801. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  8802. begin
  8803. 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);
  8804. asml.Remove(hp1);
  8805. asml.InsertBefore(hp1, p);
  8806. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  8807. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  8808. begin
  8809. taicpu(hp1).opcode := A_TEST;
  8810. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  8811. end;
  8812. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  8813. case taicpu(p).opsize of
  8814. S_BW, S_BL:
  8815. begin
  8816. SizeChange := taicpu(hp1).opsize <> S_B;
  8817. taicpu(hp1).changeopsize(S_B);
  8818. end;
  8819. S_WL:
  8820. begin
  8821. SizeChange := taicpu(hp1).opsize <> S_W;
  8822. taicpu(hp1).changeopsize(S_W);
  8823. end
  8824. else
  8825. InternalError(2020112701);
  8826. end;
  8827. UpdateUsedRegs(tai(p.Next));
  8828. { Check if the register is used aferwards - if not, we can
  8829. remove the movzx instruction completely }
  8830. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  8831. begin
  8832. { Hp1 is a better position than p for debugging purposes }
  8833. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  8834. RemoveCurrentp(p, hp1);
  8835. Result := True;
  8836. end;
  8837. if SizeChange then
  8838. DebugMsg(SPeepholeOptimization + PreMessage +
  8839. 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)
  8840. else
  8841. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  8842. Exit;
  8843. end;
  8844. { Change (using movzwl %ax,%eax as an example):
  8845. movzwl %ax, %eax
  8846. movb %al, (dest) (Register is smaller than read register in movz)
  8847. To:
  8848. movb %al, (dest) (Move one back to avoid a false dependency)
  8849. movzwl %ax, %eax
  8850. }
  8851. if (taicpu(hp1).opcode = A_MOV) and
  8852. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8853. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  8854. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  8855. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  8856. begin
  8857. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  8858. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  8859. asml.Remove(hp1);
  8860. asml.InsertBefore(hp1, p);
  8861. if taicpu(hp1).oper[1]^.typ = top_reg then
  8862. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  8863. { Check if the register is used aferwards - if not, we can
  8864. remove the movzx instruction completely }
  8865. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  8866. begin
  8867. { Hp1 is a better position than p for debugging purposes }
  8868. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  8869. RemoveCurrentp(p, hp1);
  8870. Result := True;
  8871. end;
  8872. Exit;
  8873. end;
  8874. end;
  8875. {$ifdef x86_64}
  8876. { Code size reduction by J. Gareth "Kit" Moreton }
  8877. { Convert MOVZBQ and MOVZWQ to MOVZBL and MOVZWL respectively if it removes the REX prefix }
  8878. if (taicpu(p).opsize in [S_BQ, S_WQ]) and
  8879. (getsupreg(taicpu(p).oper[1]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP])
  8880. then
  8881. begin
  8882. { Has 64-bit register name and opcode suffix }
  8883. PreMessage := 'movz' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' -> movz';
  8884. { The actual optimization }
  8885. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8886. if taicpu(p).opsize = S_BQ then
  8887. taicpu(p).changeopsize(S_BL)
  8888. else
  8889. taicpu(p).changeopsize(S_WL);
  8890. DebugMsg(SPeepholeOptimization + PreMessage +
  8891. debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (removes REX prefix)', p);
  8892. end;
  8893. {$endif}
  8894. end;
  8895. {$ifdef x86_64}
  8896. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  8897. var
  8898. PreMessage, RegName: string;
  8899. begin
  8900. { Code size reduction by J. Gareth "Kit" Moreton }
  8901. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  8902. as this removes the REX prefix }
  8903. Result := False;
  8904. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  8905. Exit;
  8906. if taicpu(p).oper[0]^.typ <> top_reg then
  8907. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  8908. InternalError(2018011500);
  8909. case taicpu(p).opsize of
  8910. S_Q:
  8911. begin
  8912. 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
  8913. begin
  8914. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  8915. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  8916. { The actual optimization }
  8917. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8918. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8919. taicpu(p).changeopsize(S_L);
  8920. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  8921. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (removes REX prefix)', p);
  8922. end;
  8923. end;
  8924. else
  8925. ;
  8926. end;
  8927. end;
  8928. {$endif}
  8929. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  8930. var
  8931. OperIdx: Integer;
  8932. begin
  8933. for OperIdx := 0 to p.ops - 1 do
  8934. if p.oper[OperIdx]^.typ = top_ref then
  8935. optimize_ref(p.oper[OperIdx]^.ref^, False);
  8936. end;
  8937. end.