aoptx86.pas 396 KB

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