aoptx86.pas 445 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407
  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. {$ifdef EXTDEBUG}
  20. {$define DEBUG_AOPTCPU}
  21. {$endif EXTDEBUG}
  22. interface
  23. uses
  24. globtype,
  25. cpubase,
  26. aasmtai,aasmcpu,
  27. cgbase,cgutils,
  28. aopt,aoptobj;
  29. type
  30. TOptsToCheck = (
  31. aoc_MovAnd2Mov_3
  32. );
  33. TX86AsmOptimizer = class(TAsmOptimizer)
  34. { some optimizations are very expensive to check, so the
  35. pre opt pass can be used to set some flags, depending on the found
  36. instructions if it is worth to check a certain optimization }
  37. OptsToCheck : set of TOptsToCheck;
  38. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  39. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  40. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  41. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  42. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  43. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  44. potentially allowing further optimisation (although it might need to know if
  45. it crossed a conditional jump. }
  46. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  47. {
  48. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  49. the use of a register by allocs/dealloc, so it can ignore calls.
  50. In the following example, GetNextInstructionUsingReg will return the second movq,
  51. GetNextInstructionUsingRegTrackingUse won't.
  52. movq %rdi,%rax
  53. # Register rdi released
  54. # Register rdi allocated
  55. movq %rax,%rdi
  56. While in this example:
  57. movq %rdi,%rax
  58. call proc
  59. movq %rdi,%rax
  60. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  61. won't.
  62. }
  63. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  64. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  65. private
  66. function SkipSimpleInstructions(var hp1: tai): Boolean;
  67. protected
  68. class function IsMOVZXAcceptable: Boolean; static; inline;
  69. { Attempts to allocate a volatile integer register for use between p and hp,
  70. using AUsedRegs for the current register usage information. Returns NR_NO
  71. if no free register could be found }
  72. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  73. { Attempts to allocate a volatile MM register for use between p and hp,
  74. using AUsedRegs for the current register usage information. Returns NR_NO
  75. if no free register could be found }
  76. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  77. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  78. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  79. { checks whether reading the value in reg1 depends on the value of reg2. This
  80. is very similar to SuperRegisterEquals, except it takes into account that
  81. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  82. depend on the value in AH). }
  83. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  84. { Replaces all references to AOldReg in a memory reference to ANewReg }
  85. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  86. { Replaces all references to AOldReg in an operand to ANewReg }
  87. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  88. { Replaces all references to AOldReg in an instruction to ANewReg,
  89. except where the register is being written }
  90. function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  91. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  92. or writes to a global symbol }
  93. class function IsRefSafe(const ref: PReference): Boolean; static; inline;
  94. { Returns true if the given MOV instruction can be safely converted to CMOV }
  95. class function CanBeCMOV(p : tai) : boolean; static;
  96. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  97. conversion was successful }
  98. function ConvertLEA(const p : taicpu): Boolean;
  99. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  100. procedure DebugMsg(const s : string; p : tai);inline;
  101. class function IsExitCode(p : tai) : boolean; static;
  102. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  103. procedure RemoveLastDeallocForFuncRes(p : tai);
  104. function DoSubAddOpt(var p : tai) : Boolean;
  105. function PrePeepholeOptSxx(var p : tai) : boolean;
  106. function PrePeepholeOptIMUL(var p : tai) : boolean;
  107. function PrePeepholeOptAND(var p : tai) : boolean;
  108. function OptPass1Test(var p: tai): boolean;
  109. function OptPass1Add(var p: tai): boolean;
  110. function OptPass1AND(var p : tai) : boolean;
  111. function OptPass1_V_MOVAP(var p : tai) : boolean;
  112. function OptPass1VOP(var p : tai) : boolean;
  113. function OptPass1MOV(var p : tai) : boolean;
  114. function OptPass1Movx(var p : tai) : boolean;
  115. function OptPass1MOVXX(var p : tai) : boolean;
  116. function OptPass1OP(var p : tai) : boolean;
  117. function OptPass1LEA(var p : tai) : boolean;
  118. function OptPass1Sub(var p : tai) : boolean;
  119. function OptPass1SHLSAL(var p : tai) : boolean;
  120. function OptPass1FSTP(var p : tai) : boolean;
  121. function OptPass1FLD(var p : tai) : boolean;
  122. function OptPass1Cmp(var p : tai) : boolean;
  123. function OptPass1PXor(var p : tai) : boolean;
  124. function OptPass1VPXor(var p: tai): boolean;
  125. function OptPass1Imul(var p : tai) : boolean;
  126. function OptPass1Jcc(var p : tai) : boolean;
  127. function OptPass1SHXX(var p: tai): boolean;
  128. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  129. function OptPass2Movx(var p : tai): Boolean;
  130. function OptPass2MOV(var p : tai) : boolean;
  131. function OptPass2Imul(var p : tai) : boolean;
  132. function OptPass2Jmp(var p : tai) : boolean;
  133. function OptPass2Jcc(var p : tai) : boolean;
  134. function OptPass2Lea(var p: tai): Boolean;
  135. function OptPass2SUB(var p: tai): Boolean;
  136. function OptPass2ADD(var p : tai): Boolean;
  137. function OptPass2SETcc(var p : tai) : boolean;
  138. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  139. function PostPeepholeOptMov(var p : tai) : Boolean;
  140. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  141. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  142. function PostPeepholeOptXor(var p : tai) : Boolean;
  143. {$endif}
  144. function PostPeepholeOptAnd(var p : tai) : boolean;
  145. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  146. function PostPeepholeOptCmp(var p : tai) : Boolean;
  147. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  148. function PostPeepholeOptCall(var p : tai) : Boolean;
  149. function PostPeepholeOptLea(var p : tai) : Boolean;
  150. function PostPeepholeOptPush(var p: tai): Boolean;
  151. function PostPeepholeOptShr(var p : tai) : boolean;
  152. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  153. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  154. procedure SwapMovCmp(var p, hp1: tai);
  155. { Processor-dependent reference optimisation }
  156. class procedure OptimizeRefs(var p: taicpu); static;
  157. end;
  158. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  159. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  160. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  161. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  162. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  163. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  164. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  165. {$if max_operands>2}
  166. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  167. {$endif max_operands>2}
  168. function RefsEqual(const r1, r2: treference): boolean;
  169. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  170. { returns true, if ref is a reference using only the registers passed as base and index
  171. and having an offset }
  172. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  173. implementation
  174. uses
  175. cutils,verbose,
  176. systems,
  177. globals,
  178. cpuinfo,
  179. procinfo,
  180. paramgr,
  181. aasmbase,
  182. aoptbase,aoptutils,
  183. symconst,symsym,
  184. cgx86,
  185. itcpugas;
  186. {$ifdef DEBUG_AOPTCPU}
  187. const
  188. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  189. {$else DEBUG_AOPTCPU}
  190. { Empty strings help the optimizer to remove string concatenations that won't
  191. ever appear to the user on release builds. [Kit] }
  192. const
  193. SPeepholeOptimization = '';
  194. {$endif DEBUG_AOPTCPU}
  195. LIST_STEP_SIZE = 4;
  196. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  197. begin
  198. result :=
  199. (instr.typ = ait_instruction) and
  200. (taicpu(instr).opcode = op) and
  201. ((opsize = []) or (taicpu(instr).opsize in opsize));
  202. end;
  203. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  204. begin
  205. result :=
  206. (instr.typ = ait_instruction) and
  207. ((taicpu(instr).opcode = op1) or
  208. (taicpu(instr).opcode = op2)
  209. ) and
  210. ((opsize = []) or (taicpu(instr).opsize in opsize));
  211. end;
  212. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  213. begin
  214. result :=
  215. (instr.typ = ait_instruction) and
  216. ((taicpu(instr).opcode = op1) or
  217. (taicpu(instr).opcode = op2) or
  218. (taicpu(instr).opcode = op3)
  219. ) and
  220. ((opsize = []) or (taicpu(instr).opsize in opsize));
  221. end;
  222. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  223. const opsize : topsizes) : boolean;
  224. var
  225. op : TAsmOp;
  226. begin
  227. result:=false;
  228. if (instr.typ <> ait_instruction) or
  229. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  230. exit;
  231. for op in ops do
  232. begin
  233. if taicpu(instr).opcode = op then
  234. begin
  235. result:=true;
  236. exit;
  237. end;
  238. end;
  239. end;
  240. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  241. begin
  242. result := (oper.typ = top_reg) and (oper.reg = reg);
  243. end;
  244. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  245. begin
  246. result := (oper.typ = top_const) and (oper.val = a);
  247. end;
  248. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  249. begin
  250. result := oper1.typ = oper2.typ;
  251. if result then
  252. case oper1.typ of
  253. top_const:
  254. Result:=oper1.val = oper2.val;
  255. top_reg:
  256. Result:=oper1.reg = oper2.reg;
  257. top_ref:
  258. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  259. else
  260. internalerror(2013102801);
  261. end
  262. end;
  263. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  264. begin
  265. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  266. if result then
  267. case oper1.typ of
  268. top_const:
  269. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  270. top_reg:
  271. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  272. top_ref:
  273. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  274. else
  275. internalerror(2020052401);
  276. end
  277. end;
  278. function RefsEqual(const r1, r2: treference): boolean;
  279. begin
  280. RefsEqual :=
  281. (r1.offset = r2.offset) and
  282. (r1.segment = r2.segment) and (r1.base = r2.base) and
  283. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  284. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  285. (r1.relsymbol = r2.relsymbol) and
  286. (r1.volatility=[]) and
  287. (r2.volatility=[]);
  288. end;
  289. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  290. begin
  291. Result:=(ref.offset=0) and
  292. (ref.scalefactor in [0,1]) and
  293. (ref.segment=NR_NO) and
  294. (ref.symbol=nil) and
  295. (ref.relsymbol=nil) and
  296. ((base=NR_INVALID) or
  297. (ref.base=base)) and
  298. ((index=NR_INVALID) or
  299. (ref.index=index)) and
  300. (ref.volatility=[]);
  301. end;
  302. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  303. begin
  304. Result:=(ref.scalefactor in [0,1]) and
  305. (ref.segment=NR_NO) and
  306. (ref.symbol=nil) and
  307. (ref.relsymbol=nil) and
  308. ((base=NR_INVALID) or
  309. (ref.base=base)) and
  310. ((index=NR_INVALID) or
  311. (ref.index=index)) and
  312. (ref.volatility=[]);
  313. end;
  314. function InstrReadsFlags(p: tai): boolean;
  315. begin
  316. InstrReadsFlags := true;
  317. case p.typ of
  318. ait_instruction:
  319. if InsProp[taicpu(p).opcode].Ch*
  320. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  321. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  322. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  323. exit;
  324. ait_label:
  325. exit;
  326. else
  327. ;
  328. end;
  329. InstrReadsFlags := false;
  330. end;
  331. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  332. begin
  333. Next:=Current;
  334. repeat
  335. Result:=GetNextInstruction(Next,Next);
  336. until not (Result) or
  337. not(cs_opt_level3 in current_settings.optimizerswitches) or
  338. (Next.typ<>ait_instruction) or
  339. RegInInstruction(reg,Next) or
  340. is_calljmp(taicpu(Next).opcode);
  341. end;
  342. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  343. begin
  344. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  345. Next := Current;
  346. repeat
  347. Result := GetNextInstruction(Next,Next);
  348. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  349. if is_calljmpuncondret(taicpu(Next).opcode) then
  350. begin
  351. Result := False;
  352. Exit;
  353. end
  354. else
  355. CrossJump := True;
  356. until not Result or
  357. not (cs_opt_level3 in current_settings.optimizerswitches) or
  358. (Next.typ <> ait_instruction) or
  359. RegInInstruction(reg,Next);
  360. end;
  361. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  362. begin
  363. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  364. begin
  365. Result:=GetNextInstruction(Current,Next);
  366. exit;
  367. end;
  368. Next:=tai(Current.Next);
  369. Result:=false;
  370. while assigned(Next) do
  371. begin
  372. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  373. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  374. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  375. exit
  376. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  377. begin
  378. Result:=true;
  379. exit;
  380. end;
  381. Next:=tai(Next.Next);
  382. end;
  383. end;
  384. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  385. begin
  386. Result:=RegReadByInstruction(reg,hp);
  387. end;
  388. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  389. var
  390. p: taicpu;
  391. opcount: longint;
  392. begin
  393. RegReadByInstruction := false;
  394. if hp.typ <> ait_instruction then
  395. exit;
  396. p := taicpu(hp);
  397. case p.opcode of
  398. A_CALL:
  399. regreadbyinstruction := true;
  400. A_IMUL:
  401. case p.ops of
  402. 1:
  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. 2,3:
  409. regReadByInstruction :=
  410. reginop(reg,p.oper[0]^) or
  411. reginop(reg,p.oper[1]^);
  412. else
  413. InternalError(2019112801);
  414. end;
  415. A_MUL:
  416. begin
  417. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  418. (
  419. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  420. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  421. );
  422. end;
  423. A_IDIV,A_DIV:
  424. begin
  425. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  426. (
  427. (getregtype(reg)=R_INTREGISTER) and
  428. (
  429. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  430. )
  431. );
  432. end;
  433. else
  434. begin
  435. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  436. begin
  437. RegReadByInstruction := false;
  438. exit;
  439. end;
  440. for opcount := 0 to p.ops-1 do
  441. if (p.oper[opCount]^.typ = top_ref) and
  442. RegInRef(reg,p.oper[opcount]^.ref^) then
  443. begin
  444. RegReadByInstruction := true;
  445. exit
  446. end;
  447. { special handling for SSE MOVSD }
  448. if (p.opcode=A_MOVSD) and (p.ops>0) then
  449. begin
  450. if p.ops<>2 then
  451. internalerror(2017042702);
  452. regReadByInstruction := reginop(reg,p.oper[0]^) or
  453. (
  454. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  455. );
  456. exit;
  457. end;
  458. with insprop[p.opcode] do
  459. begin
  460. case getregtype(reg) of
  461. R_INTREGISTER:
  462. begin
  463. case getsupreg(reg) of
  464. RS_EAX:
  465. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  466. begin
  467. RegReadByInstruction := true;
  468. exit
  469. end;
  470. RS_ECX:
  471. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  472. begin
  473. RegReadByInstruction := true;
  474. exit
  475. end;
  476. RS_EDX:
  477. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  478. begin
  479. RegReadByInstruction := true;
  480. exit
  481. end;
  482. RS_EBX:
  483. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  484. begin
  485. RegReadByInstruction := true;
  486. exit
  487. end;
  488. RS_ESP:
  489. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  490. begin
  491. RegReadByInstruction := true;
  492. exit
  493. end;
  494. RS_EBP:
  495. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  496. begin
  497. RegReadByInstruction := true;
  498. exit
  499. end;
  500. RS_ESI:
  501. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  502. begin
  503. RegReadByInstruction := true;
  504. exit
  505. end;
  506. RS_EDI:
  507. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  508. begin
  509. RegReadByInstruction := true;
  510. exit
  511. end;
  512. end;
  513. end;
  514. R_MMREGISTER:
  515. begin
  516. case getsupreg(reg) of
  517. RS_XMM0:
  518. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  519. begin
  520. RegReadByInstruction := true;
  521. exit
  522. end;
  523. end;
  524. end;
  525. else
  526. ;
  527. end;
  528. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  529. begin
  530. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  531. begin
  532. case p.condition of
  533. C_A,C_NBE, { CF=0 and ZF=0 }
  534. C_BE,C_NA: { CF=1 or ZF=1 }
  535. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  536. C_AE,C_NB,C_NC, { CF=0 }
  537. C_B,C_NAE,C_C: { CF=1 }
  538. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  539. C_NE,C_NZ, { ZF=0 }
  540. C_E,C_Z: { ZF=1 }
  541. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  542. C_G,C_NLE, { ZF=0 and SF=OF }
  543. C_LE,C_NG: { ZF=1 or SF<>OF }
  544. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  545. C_GE,C_NL, { SF=OF }
  546. C_L,C_NGE: { SF<>OF }
  547. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  548. C_NO, { OF=0 }
  549. C_O: { OF=1 }
  550. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  551. C_NP,C_PO, { PF=0 }
  552. C_P,C_PE: { PF=1 }
  553. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  554. C_NS, { SF=0 }
  555. C_S: { SF=1 }
  556. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  557. else
  558. internalerror(2017042701);
  559. end;
  560. if RegReadByInstruction then
  561. exit;
  562. end;
  563. case getsubreg(reg) of
  564. R_SUBW,R_SUBD,R_SUBQ:
  565. RegReadByInstruction :=
  566. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  567. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  568. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  569. R_SUBFLAGCARRY:
  570. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  571. R_SUBFLAGPARITY:
  572. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  573. R_SUBFLAGAUXILIARY:
  574. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  575. R_SUBFLAGZERO:
  576. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  577. R_SUBFLAGSIGN:
  578. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  579. R_SUBFLAGOVERFLOW:
  580. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  581. R_SUBFLAGINTERRUPT:
  582. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  583. R_SUBFLAGDIRECTION:
  584. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  585. else
  586. internalerror(2017042601);
  587. end;
  588. exit;
  589. end;
  590. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  591. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  592. (p.oper[0]^.reg=p.oper[1]^.reg) then
  593. exit;
  594. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  595. begin
  596. RegReadByInstruction := true;
  597. exit
  598. end;
  599. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  600. begin
  601. RegReadByInstruction := true;
  602. exit
  603. end;
  604. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  605. begin
  606. RegReadByInstruction := true;
  607. exit
  608. end;
  609. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  610. begin
  611. RegReadByInstruction := true;
  612. exit
  613. end;
  614. end;
  615. end;
  616. end;
  617. end;
  618. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  619. begin
  620. result:=false;
  621. if p1.typ<>ait_instruction then
  622. exit;
  623. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  624. exit(true);
  625. if (getregtype(reg)=R_INTREGISTER) and
  626. { change information for xmm movsd are not correct }
  627. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  628. begin
  629. case getsupreg(reg) of
  630. { RS_EAX = RS_RAX on x86-64 }
  631. RS_EAX:
  632. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  633. RS_ECX:
  634. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  635. RS_EDX:
  636. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  637. RS_EBX:
  638. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  639. RS_ESP:
  640. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  641. RS_EBP:
  642. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  643. RS_ESI:
  644. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  645. RS_EDI:
  646. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  647. else
  648. ;
  649. end;
  650. if result then
  651. exit;
  652. end
  653. else if getregtype(reg)=R_MMREGISTER then
  654. begin
  655. case getsupreg(reg) of
  656. RS_XMM0:
  657. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  658. else
  659. ;
  660. end;
  661. if result then
  662. exit;
  663. end
  664. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  665. begin
  666. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  667. exit(true);
  668. case getsubreg(reg) of
  669. R_SUBFLAGCARRY:
  670. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  671. R_SUBFLAGPARITY:
  672. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  673. R_SUBFLAGAUXILIARY:
  674. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  675. R_SUBFLAGZERO:
  676. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  677. R_SUBFLAGSIGN:
  678. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  679. R_SUBFLAGOVERFLOW:
  680. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  681. R_SUBFLAGINTERRUPT:
  682. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  683. R_SUBFLAGDIRECTION:
  684. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  685. else
  686. ;
  687. end;
  688. if result then
  689. exit;
  690. end
  691. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  692. exit(true);
  693. Result:=inherited RegInInstruction(Reg, p1);
  694. end;
  695. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  696. begin
  697. Result := False;
  698. if p1.typ <> ait_instruction then
  699. exit;
  700. with insprop[taicpu(p1).opcode] do
  701. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  702. begin
  703. case getsubreg(reg) of
  704. R_SUBW,R_SUBD,R_SUBQ:
  705. Result :=
  706. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  707. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  708. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  709. R_SUBFLAGCARRY:
  710. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  711. R_SUBFLAGPARITY:
  712. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  713. R_SUBFLAGAUXILIARY:
  714. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  715. R_SUBFLAGZERO:
  716. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  717. R_SUBFLAGSIGN:
  718. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  719. R_SUBFLAGOVERFLOW:
  720. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  721. R_SUBFLAGINTERRUPT:
  722. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  723. R_SUBFLAGDIRECTION:
  724. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  725. else
  726. internalerror(2017042602);
  727. end;
  728. exit;
  729. end;
  730. case taicpu(p1).opcode of
  731. A_CALL:
  732. { We could potentially set Result to False if the register in
  733. question is non-volatile for the subroutine's calling convention,
  734. but this would require detecting the calling convention in use and
  735. also assuming that the routine doesn't contain malformed assembly
  736. language, for example... so it could only be done under -O4 as it
  737. would be considered a side-effect. [Kit] }
  738. Result := True;
  739. A_MOVSD:
  740. { special handling for SSE MOVSD }
  741. if (taicpu(p1).ops>0) then
  742. begin
  743. if taicpu(p1).ops<>2 then
  744. internalerror(2017042703);
  745. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  746. end;
  747. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  748. so fix it here (FK)
  749. }
  750. A_VMOVSS,
  751. A_VMOVSD:
  752. begin
  753. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  754. exit;
  755. end;
  756. A_IMUL:
  757. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  758. else
  759. ;
  760. end;
  761. if Result then
  762. exit;
  763. with insprop[taicpu(p1).opcode] do
  764. begin
  765. if getregtype(reg)=R_INTREGISTER then
  766. begin
  767. case getsupreg(reg) of
  768. RS_EAX:
  769. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  770. begin
  771. Result := True;
  772. exit
  773. end;
  774. RS_ECX:
  775. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  776. begin
  777. Result := True;
  778. exit
  779. end;
  780. RS_EDX:
  781. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  782. begin
  783. Result := True;
  784. exit
  785. end;
  786. RS_EBX:
  787. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  788. begin
  789. Result := True;
  790. exit
  791. end;
  792. RS_ESP:
  793. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  794. begin
  795. Result := True;
  796. exit
  797. end;
  798. RS_EBP:
  799. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  800. begin
  801. Result := True;
  802. exit
  803. end;
  804. RS_ESI:
  805. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  806. begin
  807. Result := True;
  808. exit
  809. end;
  810. RS_EDI:
  811. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  812. begin
  813. Result := True;
  814. exit
  815. end;
  816. end;
  817. end;
  818. if ([CH_RWOP1,CH_WOP1,CH_MOP1]*Ch<>[]) and reginop(reg,taicpu(p1).oper[0]^) then
  819. begin
  820. Result := true;
  821. exit
  822. end;
  823. if ([Ch_RWOP2,Ch_WOP2,Ch_MOP2]*Ch<>[]) and reginop(reg,taicpu(p1).oper[1]^) then
  824. begin
  825. Result := true;
  826. exit
  827. end;
  828. if ([Ch_RWOP3,Ch_WOP3,Ch_MOP3]*Ch<>[]) and reginop(reg,taicpu(p1).oper[2]^) then
  829. begin
  830. Result := true;
  831. exit
  832. end;
  833. if ([Ch_RWOP4,Ch_WOP4,Ch_MOP4]*Ch<>[]) and reginop(reg,taicpu(p1).oper[3]^) then
  834. begin
  835. Result := true;
  836. exit
  837. end;
  838. end;
  839. end;
  840. {$ifdef DEBUG_AOPTCPU}
  841. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  842. begin
  843. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  844. end;
  845. function debug_tostr(i: tcgint): string; inline;
  846. begin
  847. Result := tostr(i);
  848. end;
  849. function debug_regname(r: TRegister): string; inline;
  850. begin
  851. Result := '%' + std_regname(r);
  852. end;
  853. { Debug output function - creates a string representation of an operator }
  854. function debug_operstr(oper: TOper): string;
  855. begin
  856. case oper.typ of
  857. top_const:
  858. Result := '$' + debug_tostr(oper.val);
  859. top_reg:
  860. Result := debug_regname(oper.reg);
  861. top_ref:
  862. begin
  863. if oper.ref^.offset <> 0 then
  864. Result := debug_tostr(oper.ref^.offset) + '('
  865. else
  866. Result := '(';
  867. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  868. begin
  869. Result := Result + debug_regname(oper.ref^.base);
  870. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  871. Result := Result + ',' + debug_regname(oper.ref^.index);
  872. end
  873. else
  874. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  875. Result := Result + debug_regname(oper.ref^.index);
  876. if (oper.ref^.scalefactor > 1) then
  877. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  878. else
  879. Result := Result + ')';
  880. end;
  881. else
  882. Result := '[UNKNOWN]';
  883. end;
  884. end;
  885. function debug_op2str(opcode: tasmop): string; inline;
  886. begin
  887. Result := std_op2str[opcode];
  888. end;
  889. function debug_opsize2str(opsize: topsize): string; inline;
  890. begin
  891. Result := gas_opsize2str[opsize];
  892. end;
  893. {$else DEBUG_AOPTCPU}
  894. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  895. begin
  896. end;
  897. function debug_tostr(i: tcgint): string; inline;
  898. begin
  899. Result := '';
  900. end;
  901. function debug_regname(r: TRegister): string; inline;
  902. begin
  903. Result := '';
  904. end;
  905. function debug_operstr(oper: TOper): string; inline;
  906. begin
  907. Result := '';
  908. end;
  909. function debug_op2str(opcode: tasmop): string; inline;
  910. begin
  911. Result := '';
  912. end;
  913. function debug_opsize2str(opsize: topsize): string; inline;
  914. begin
  915. Result := '';
  916. end;
  917. {$endif DEBUG_AOPTCPU}
  918. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  919. begin
  920. {$ifdef x86_64}
  921. { Always fine on x86-64 }
  922. Result := True;
  923. {$else x86_64}
  924. Result :=
  925. {$ifdef i8086}
  926. (current_settings.cputype >= cpu_386) and
  927. {$endif i8086}
  928. (
  929. { Always accept if optimising for size }
  930. (cs_opt_size in current_settings.optimizerswitches) or
  931. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  932. (current_settings.optimizecputype >= cpu_Pentium2)
  933. );
  934. {$endif x86_64}
  935. end;
  936. { Attempts to allocate a volatile integer register for use between p and hp,
  937. using AUsedRegs for the current register usage information. Returns NR_NO
  938. if no free register could be found }
  939. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  940. var
  941. RegSet: TCPURegisterSet;
  942. CurrentSuperReg: Integer;
  943. CurrentReg: TRegister;
  944. Currentp: tai;
  945. Breakout: Boolean;
  946. begin
  947. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  948. Result := NR_NO;
  949. RegSet := paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption);
  950. for CurrentSuperReg in RegSet do
  951. begin
  952. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  953. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg) then
  954. begin
  955. Currentp := p;
  956. Breakout := False;
  957. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  958. begin
  959. case Currentp.typ of
  960. ait_instruction:
  961. begin
  962. if RegInInstruction(CurrentReg, Currentp) then
  963. begin
  964. Breakout := True;
  965. Break;
  966. end;
  967. { Cannot allocate across an unconditional jump }
  968. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  969. Exit;
  970. end;
  971. ait_marker:
  972. { Don't try anything more if a marker is hit }
  973. Exit;
  974. ait_regalloc:
  975. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  976. begin
  977. Breakout := True;
  978. Break;
  979. end;
  980. else
  981. ;
  982. end;
  983. end;
  984. if Breakout then
  985. { Try the next register }
  986. Continue;
  987. { We have a free register available }
  988. Result := CurrentReg;
  989. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  990. Exit;
  991. end;
  992. end;
  993. end;
  994. { Attempts to allocate a volatile MM register for use between p and hp,
  995. using AUsedRegs for the current register usage information. Returns NR_NO
  996. if no free register could be found }
  997. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  998. var
  999. RegSet: TCPURegisterSet;
  1000. CurrentSuperReg: Integer;
  1001. CurrentReg: TRegister;
  1002. Currentp: tai;
  1003. Breakout: Boolean;
  1004. begin
  1005. { TODO: Currently, only the volatile registers are checked - can this be extended to use any register the procedure has preserved? }
  1006. Result := NR_NO;
  1007. RegSet := paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption);
  1008. for CurrentSuperReg in RegSet do
  1009. begin
  1010. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1011. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1012. begin
  1013. Currentp := p;
  1014. Breakout := False;
  1015. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1016. begin
  1017. case Currentp.typ of
  1018. ait_instruction:
  1019. begin
  1020. if RegInInstruction(CurrentReg, Currentp) then
  1021. begin
  1022. Breakout := True;
  1023. Break;
  1024. end;
  1025. { Cannot allocate across an unconditional jump }
  1026. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1027. Exit;
  1028. end;
  1029. ait_marker:
  1030. { Don't try anything more if a marker is hit }
  1031. Exit;
  1032. ait_regalloc:
  1033. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1034. begin
  1035. Breakout := True;
  1036. Break;
  1037. end;
  1038. else
  1039. ;
  1040. end;
  1041. end;
  1042. if Breakout then
  1043. { Try the next register }
  1044. Continue;
  1045. { We have a free register available }
  1046. Result := CurrentReg;
  1047. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1048. Exit;
  1049. end;
  1050. end;
  1051. end;
  1052. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1053. begin
  1054. if not SuperRegistersEqual(reg1,reg2) then
  1055. exit(false);
  1056. if getregtype(reg1)<>R_INTREGISTER then
  1057. exit(true); {because SuperRegisterEqual is true}
  1058. case getsubreg(reg1) of
  1059. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1060. higher, it preserves the high bits, so the new value depends on
  1061. reg2's previous value. In other words, it is equivalent to doing:
  1062. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1063. R_SUBL:
  1064. exit(getsubreg(reg2)=R_SUBL);
  1065. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1066. higher, it actually does a:
  1067. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1068. R_SUBH:
  1069. exit(getsubreg(reg2)=R_SUBH);
  1070. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1071. bits of reg2:
  1072. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1073. R_SUBW:
  1074. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1075. { a write to R_SUBD always overwrites every other subregister,
  1076. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1077. R_SUBD,
  1078. R_SUBQ:
  1079. exit(true);
  1080. else
  1081. internalerror(2017042801);
  1082. end;
  1083. end;
  1084. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1085. begin
  1086. if not SuperRegistersEqual(reg1,reg2) then
  1087. exit(false);
  1088. if getregtype(reg1)<>R_INTREGISTER then
  1089. exit(true); {because SuperRegisterEqual is true}
  1090. case getsubreg(reg1) of
  1091. R_SUBL:
  1092. exit(getsubreg(reg2)<>R_SUBH);
  1093. R_SUBH:
  1094. exit(getsubreg(reg2)<>R_SUBL);
  1095. R_SUBW,
  1096. R_SUBD,
  1097. R_SUBQ:
  1098. exit(true);
  1099. else
  1100. internalerror(2017042802);
  1101. end;
  1102. end;
  1103. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1104. var
  1105. hp1 : tai;
  1106. l : TCGInt;
  1107. begin
  1108. result:=false;
  1109. { changes the code sequence
  1110. shr/sar const1, x
  1111. shl const2, x
  1112. to
  1113. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1114. if GetNextInstruction(p, hp1) and
  1115. MatchInstruction(hp1,A_SHL,[]) and
  1116. (taicpu(p).oper[0]^.typ = top_const) and
  1117. (taicpu(hp1).oper[0]^.typ = top_const) and
  1118. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1119. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1120. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1121. begin
  1122. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1123. not(cs_opt_size in current_settings.optimizerswitches) then
  1124. begin
  1125. { shr/sar const1, %reg
  1126. shl const2, %reg
  1127. with const1 > const2 }
  1128. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1129. taicpu(hp1).opcode := A_AND;
  1130. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1131. case taicpu(p).opsize Of
  1132. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1133. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1134. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1135. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1136. else
  1137. Internalerror(2017050703)
  1138. end;
  1139. end
  1140. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1141. not(cs_opt_size in current_settings.optimizerswitches) then
  1142. begin
  1143. { shr/sar const1, %reg
  1144. shl const2, %reg
  1145. with const1 < const2 }
  1146. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1147. taicpu(p).opcode := A_AND;
  1148. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1149. case taicpu(p).opsize Of
  1150. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1151. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1152. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1153. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1154. else
  1155. Internalerror(2017050702)
  1156. end;
  1157. end
  1158. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1159. begin
  1160. { shr/sar const1, %reg
  1161. shl const2, %reg
  1162. with const1 = const2 }
  1163. taicpu(p).opcode := A_AND;
  1164. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1165. case taicpu(p).opsize Of
  1166. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1167. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1168. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1169. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1170. else
  1171. Internalerror(2017050701)
  1172. end;
  1173. RemoveInstruction(hp1);
  1174. end;
  1175. end;
  1176. end;
  1177. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1178. var
  1179. opsize : topsize;
  1180. hp1 : tai;
  1181. tmpref : treference;
  1182. ShiftValue : Cardinal;
  1183. BaseValue : TCGInt;
  1184. begin
  1185. result:=false;
  1186. opsize:=taicpu(p).opsize;
  1187. { changes certain "imul const, %reg"'s to lea sequences }
  1188. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1189. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1190. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1191. if (taicpu(p).oper[0]^.val = 1) then
  1192. if (taicpu(p).ops = 2) then
  1193. { remove "imul $1, reg" }
  1194. begin
  1195. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1196. Result := RemoveCurrentP(p);
  1197. end
  1198. else
  1199. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1200. begin
  1201. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1202. InsertLLItem(p.previous, p.next, hp1);
  1203. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1204. p.free;
  1205. p := hp1;
  1206. end
  1207. else if ((taicpu(p).ops <= 2) or
  1208. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1209. not(cs_opt_size in current_settings.optimizerswitches) and
  1210. (not(GetNextInstruction(p, hp1)) or
  1211. not((tai(hp1).typ = ait_instruction) and
  1212. ((taicpu(hp1).opcode=A_Jcc) and
  1213. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1214. begin
  1215. {
  1216. imul X, reg1, reg2 to
  1217. lea (reg1,reg1,Y), reg2
  1218. shl ZZ,reg2
  1219. imul XX, reg1 to
  1220. lea (reg1,reg1,YY), reg1
  1221. shl ZZ,reg2
  1222. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1223. it does not exist as a separate optimization target in FPC though.
  1224. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1225. at most two zeros
  1226. }
  1227. reference_reset(tmpref,1,[]);
  1228. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1229. begin
  1230. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1231. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1232. TmpRef.base := taicpu(p).oper[1]^.reg;
  1233. TmpRef.index := taicpu(p).oper[1]^.reg;
  1234. if not(BaseValue in [3,5,9]) then
  1235. Internalerror(2018110101);
  1236. TmpRef.ScaleFactor := BaseValue-1;
  1237. if (taicpu(p).ops = 2) then
  1238. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1239. else
  1240. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1241. AsmL.InsertAfter(hp1,p);
  1242. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1243. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1244. RemoveCurrentP(p, hp1);
  1245. if ShiftValue>0 then
  1246. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1247. end;
  1248. end;
  1249. end;
  1250. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1251. begin
  1252. Result := False;
  1253. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1254. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1255. begin
  1256. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1257. taicpu(p).opcode := A_MOV;
  1258. Result := True;
  1259. end;
  1260. end;
  1261. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1262. var
  1263. p: taicpu absolute hp;
  1264. i: Integer;
  1265. begin
  1266. Result := False;
  1267. if not assigned(hp) or
  1268. (hp.typ <> ait_instruction) then
  1269. Exit;
  1270. // p := taicpu(hp);
  1271. Prefetch(insprop[p.opcode]);
  1272. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1273. with insprop[p.opcode] do
  1274. begin
  1275. case getsubreg(reg) of
  1276. R_SUBW,R_SUBD,R_SUBQ:
  1277. Result:=
  1278. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1279. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1280. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1281. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1282. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1283. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1284. R_SUBFLAGCARRY:
  1285. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1286. R_SUBFLAGPARITY:
  1287. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1288. R_SUBFLAGAUXILIARY:
  1289. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1290. R_SUBFLAGZERO:
  1291. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1292. R_SUBFLAGSIGN:
  1293. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1294. R_SUBFLAGOVERFLOW:
  1295. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1296. R_SUBFLAGINTERRUPT:
  1297. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1298. R_SUBFLAGDIRECTION:
  1299. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1300. else
  1301. begin
  1302. writeln(getsubreg(reg));
  1303. internalerror(2017050501);
  1304. end;
  1305. end;
  1306. exit;
  1307. end;
  1308. { Handle special cases first }
  1309. case p.opcode of
  1310. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1311. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1312. begin
  1313. Result :=
  1314. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1315. (p.oper[1]^.typ = top_reg) and
  1316. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1317. (
  1318. (p.oper[0]^.typ = top_const) or
  1319. (
  1320. (p.oper[0]^.typ = top_reg) and
  1321. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1322. ) or (
  1323. (p.oper[0]^.typ = top_ref) and
  1324. not RegInRef(reg,p.oper[0]^.ref^)
  1325. )
  1326. );
  1327. end;
  1328. A_MUL, A_IMUL:
  1329. Result :=
  1330. (
  1331. (p.ops=3) and { IMUL only }
  1332. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1333. (
  1334. (
  1335. (p.oper[1]^.typ=top_reg) and
  1336. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1337. ) or (
  1338. (p.oper[1]^.typ=top_ref) and
  1339. not RegInRef(reg,p.oper[1]^.ref^)
  1340. )
  1341. )
  1342. ) or (
  1343. (
  1344. (p.ops=1) and
  1345. (
  1346. (
  1347. (
  1348. (p.oper[0]^.typ=top_reg) and
  1349. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1350. )
  1351. ) or (
  1352. (p.oper[0]^.typ=top_ref) and
  1353. not RegInRef(reg,p.oper[0]^.ref^)
  1354. )
  1355. ) and (
  1356. (
  1357. (p.opsize=S_B) and
  1358. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1359. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1360. ) or (
  1361. (p.opsize=S_W) and
  1362. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1363. ) or (
  1364. (p.opsize=S_L) and
  1365. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1366. {$ifdef x86_64}
  1367. ) or (
  1368. (p.opsize=S_Q) and
  1369. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1370. {$endif x86_64}
  1371. )
  1372. )
  1373. )
  1374. );
  1375. A_CBW:
  1376. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1377. {$ifndef x86_64}
  1378. A_LDS:
  1379. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1380. A_LES:
  1381. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1382. {$endif not x86_64}
  1383. A_LFS:
  1384. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1385. A_LGS:
  1386. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1387. A_LSS:
  1388. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1389. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1390. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1391. A_LODSB:
  1392. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1393. A_LODSW:
  1394. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1395. {$ifdef x86_64}
  1396. A_LODSQ:
  1397. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1398. {$endif x86_64}
  1399. A_LODSD:
  1400. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1401. A_FSTSW, A_FNSTSW:
  1402. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1403. else
  1404. begin
  1405. with insprop[p.opcode] do
  1406. begin
  1407. if (
  1408. { xor %reg,%reg etc. is classed as a new value }
  1409. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1410. MatchOpType(p, top_reg, top_reg) and
  1411. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1412. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1413. ) then
  1414. begin
  1415. Result := True;
  1416. Exit;
  1417. end;
  1418. { Make sure the entire register is overwritten }
  1419. if (getregtype(reg) = R_INTREGISTER) then
  1420. begin
  1421. if (p.ops > 0) then
  1422. begin
  1423. if RegInOp(reg, p.oper[0]^) then
  1424. begin
  1425. if (p.oper[0]^.typ = top_ref) then
  1426. begin
  1427. if RegInRef(reg, p.oper[0]^.ref^) then
  1428. begin
  1429. Result := False;
  1430. Exit;
  1431. end;
  1432. end
  1433. else if (p.oper[0]^.typ = top_reg) then
  1434. begin
  1435. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1436. begin
  1437. Result := False;
  1438. Exit;
  1439. end
  1440. else if ([Ch_WOp1]*Ch<>[]) then
  1441. begin
  1442. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1443. Result := True
  1444. else
  1445. begin
  1446. Result := False;
  1447. Exit;
  1448. end;
  1449. end;
  1450. end;
  1451. end;
  1452. if (p.ops > 1) then
  1453. begin
  1454. if RegInOp(reg, p.oper[1]^) then
  1455. begin
  1456. if (p.oper[1]^.typ = top_ref) then
  1457. begin
  1458. if RegInRef(reg, p.oper[1]^.ref^) then
  1459. begin
  1460. Result := False;
  1461. Exit;
  1462. end;
  1463. end
  1464. else if (p.oper[1]^.typ = top_reg) then
  1465. begin
  1466. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1467. begin
  1468. Result := False;
  1469. Exit;
  1470. end
  1471. else if ([Ch_WOp2]*Ch<>[]) then
  1472. begin
  1473. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1474. Result := True
  1475. else
  1476. begin
  1477. Result := False;
  1478. Exit;
  1479. end;
  1480. end;
  1481. end;
  1482. end;
  1483. if (p.ops > 2) then
  1484. begin
  1485. if RegInOp(reg, p.oper[2]^) then
  1486. begin
  1487. if (p.oper[2]^.typ = top_ref) then
  1488. begin
  1489. if RegInRef(reg, p.oper[2]^.ref^) then
  1490. begin
  1491. Result := False;
  1492. Exit;
  1493. end;
  1494. end
  1495. else if (p.oper[2]^.typ = top_reg) then
  1496. begin
  1497. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1498. begin
  1499. Result := False;
  1500. Exit;
  1501. end
  1502. else if ([Ch_WOp3]*Ch<>[]) then
  1503. begin
  1504. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1505. Result := True
  1506. else
  1507. begin
  1508. Result := False;
  1509. Exit;
  1510. end;
  1511. end;
  1512. end;
  1513. end;
  1514. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1515. begin
  1516. if (p.oper[3]^.typ = top_ref) then
  1517. begin
  1518. if RegInRef(reg, p.oper[3]^.ref^) then
  1519. begin
  1520. Result := False;
  1521. Exit;
  1522. end;
  1523. end
  1524. else if (p.oper[3]^.typ = top_reg) then
  1525. begin
  1526. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1527. begin
  1528. Result := False;
  1529. Exit;
  1530. end
  1531. else if ([Ch_WOp4]*Ch<>[]) then
  1532. begin
  1533. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1534. Result := True
  1535. else
  1536. begin
  1537. Result := False;
  1538. Exit;
  1539. end;
  1540. end;
  1541. end;
  1542. end;
  1543. end;
  1544. end;
  1545. end;
  1546. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1547. case getsupreg(reg) of
  1548. RS_EAX:
  1549. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1550. begin
  1551. Result := True;
  1552. Exit;
  1553. end;
  1554. RS_ECX:
  1555. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1556. begin
  1557. Result := True;
  1558. Exit;
  1559. end;
  1560. RS_EDX:
  1561. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1562. begin
  1563. Result := True;
  1564. Exit;
  1565. end;
  1566. RS_EBX:
  1567. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1568. begin
  1569. Result := True;
  1570. Exit;
  1571. end;
  1572. RS_ESP:
  1573. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1574. begin
  1575. Result := True;
  1576. Exit;
  1577. end;
  1578. RS_EBP:
  1579. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1580. begin
  1581. Result := True;
  1582. Exit;
  1583. end;
  1584. RS_ESI:
  1585. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1586. begin
  1587. Result := True;
  1588. Exit;
  1589. end;
  1590. RS_EDI:
  1591. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1592. begin
  1593. Result := True;
  1594. Exit;
  1595. end;
  1596. else
  1597. ;
  1598. end;
  1599. end;
  1600. end;
  1601. end;
  1602. end;
  1603. end;
  1604. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1605. var
  1606. hp2,hp3 : tai;
  1607. begin
  1608. { some x86-64 issue a NOP before the real exit code }
  1609. if MatchInstruction(p,A_NOP,[]) then
  1610. GetNextInstruction(p,p);
  1611. result:=assigned(p) and (p.typ=ait_instruction) and
  1612. ((taicpu(p).opcode = A_RET) or
  1613. ((taicpu(p).opcode=A_LEAVE) and
  1614. GetNextInstruction(p,hp2) and
  1615. MatchInstruction(hp2,A_RET,[S_NO])
  1616. ) or
  1617. (((taicpu(p).opcode=A_LEA) and
  1618. MatchOpType(taicpu(p),top_ref,top_reg) and
  1619. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1620. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1621. ) and
  1622. GetNextInstruction(p,hp2) and
  1623. MatchInstruction(hp2,A_RET,[S_NO])
  1624. ) or
  1625. ((((taicpu(p).opcode=A_MOV) and
  1626. MatchOpType(taicpu(p),top_reg,top_reg) and
  1627. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1628. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1629. ((taicpu(p).opcode=A_LEA) and
  1630. MatchOpType(taicpu(p),top_ref,top_reg) and
  1631. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1632. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1633. )
  1634. ) and
  1635. GetNextInstruction(p,hp2) and
  1636. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1637. MatchOpType(taicpu(hp2),top_reg) and
  1638. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1639. GetNextInstruction(hp2,hp3) and
  1640. MatchInstruction(hp3,A_RET,[S_NO])
  1641. )
  1642. );
  1643. end;
  1644. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1645. begin
  1646. isFoldableArithOp := False;
  1647. case hp1.opcode of
  1648. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1649. isFoldableArithOp :=
  1650. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1651. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1652. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1653. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1654. (taicpu(hp1).oper[1]^.reg = reg);
  1655. A_INC,A_DEC,A_NEG,A_NOT:
  1656. isFoldableArithOp :=
  1657. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1658. (taicpu(hp1).oper[0]^.reg = reg);
  1659. else
  1660. ;
  1661. end;
  1662. end;
  1663. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1664. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1665. var
  1666. hp2: tai;
  1667. begin
  1668. hp2 := p;
  1669. repeat
  1670. hp2 := tai(hp2.previous);
  1671. if assigned(hp2) and
  1672. (hp2.typ = ait_regalloc) and
  1673. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1674. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1675. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1676. begin
  1677. RemoveInstruction(hp2);
  1678. break;
  1679. end;
  1680. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1681. end;
  1682. begin
  1683. case current_procinfo.procdef.returndef.typ of
  1684. arraydef,recorddef,pointerdef,
  1685. stringdef,enumdef,procdef,objectdef,errordef,
  1686. filedef,setdef,procvardef,
  1687. classrefdef,forwarddef:
  1688. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1689. orddef:
  1690. if current_procinfo.procdef.returndef.size <> 0 then
  1691. begin
  1692. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1693. { for int64/qword }
  1694. if current_procinfo.procdef.returndef.size = 8 then
  1695. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1696. end;
  1697. else
  1698. ;
  1699. end;
  1700. end;
  1701. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1702. var
  1703. hp1,hp2 : tai;
  1704. begin
  1705. result:=false;
  1706. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1707. begin
  1708. { vmova* reg1,reg1
  1709. =>
  1710. <nop> }
  1711. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1712. begin
  1713. RemoveCurrentP(p);
  1714. result:=true;
  1715. exit;
  1716. end
  1717. else if GetNextInstruction(p,hp1) then
  1718. begin
  1719. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1720. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1721. begin
  1722. { vmova* reg1,reg2
  1723. vmova* reg2,reg3
  1724. dealloc reg2
  1725. =>
  1726. vmova* reg1,reg3 }
  1727. TransferUsedRegs(TmpUsedRegs);
  1728. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1729. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1730. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1731. begin
  1732. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1733. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1734. RemoveInstruction(hp1);
  1735. result:=true;
  1736. exit;
  1737. end
  1738. { special case:
  1739. vmova* reg1,<op>
  1740. vmova* <op>,reg1
  1741. =>
  1742. vmova* reg1,<op> }
  1743. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1744. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1745. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1746. ) then
  1747. begin
  1748. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1749. RemoveInstruction(hp1);
  1750. result:=true;
  1751. exit;
  1752. end
  1753. end
  1754. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1755. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1756. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1757. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1758. ) and
  1759. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1760. begin
  1761. { vmova* reg1,reg2
  1762. vmovs* reg2,<op>
  1763. dealloc reg2
  1764. =>
  1765. vmovs* reg1,reg3 }
  1766. TransferUsedRegs(TmpUsedRegs);
  1767. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1768. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1769. begin
  1770. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1771. taicpu(p).opcode:=taicpu(hp1).opcode;
  1772. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1773. RemoveInstruction(hp1);
  1774. result:=true;
  1775. exit;
  1776. end
  1777. end;
  1778. end;
  1779. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1780. begin
  1781. if MatchInstruction(hp1,[A_VFMADDPD,
  1782. A_VFMADD132PD,
  1783. A_VFMADD132PS,
  1784. A_VFMADD132SD,
  1785. A_VFMADD132SS,
  1786. A_VFMADD213PD,
  1787. A_VFMADD213PS,
  1788. A_VFMADD213SD,
  1789. A_VFMADD213SS,
  1790. A_VFMADD231PD,
  1791. A_VFMADD231PS,
  1792. A_VFMADD231SD,
  1793. A_VFMADD231SS,
  1794. A_VFMADDSUB132PD,
  1795. A_VFMADDSUB132PS,
  1796. A_VFMADDSUB213PD,
  1797. A_VFMADDSUB213PS,
  1798. A_VFMADDSUB231PD,
  1799. A_VFMADDSUB231PS,
  1800. A_VFMSUB132PD,
  1801. A_VFMSUB132PS,
  1802. A_VFMSUB132SD,
  1803. A_VFMSUB132SS,
  1804. A_VFMSUB213PD,
  1805. A_VFMSUB213PS,
  1806. A_VFMSUB213SD,
  1807. A_VFMSUB213SS,
  1808. A_VFMSUB231PD,
  1809. A_VFMSUB231PS,
  1810. A_VFMSUB231SD,
  1811. A_VFMSUB231SS,
  1812. A_VFMSUBADD132PD,
  1813. A_VFMSUBADD132PS,
  1814. A_VFMSUBADD213PD,
  1815. A_VFMSUBADD213PS,
  1816. A_VFMSUBADD231PD,
  1817. A_VFMSUBADD231PS,
  1818. A_VFNMADD132PD,
  1819. A_VFNMADD132PS,
  1820. A_VFNMADD132SD,
  1821. A_VFNMADD132SS,
  1822. A_VFNMADD213PD,
  1823. A_VFNMADD213PS,
  1824. A_VFNMADD213SD,
  1825. A_VFNMADD213SS,
  1826. A_VFNMADD231PD,
  1827. A_VFNMADD231PS,
  1828. A_VFNMADD231SD,
  1829. A_VFNMADD231SS,
  1830. A_VFNMSUB132PD,
  1831. A_VFNMSUB132PS,
  1832. A_VFNMSUB132SD,
  1833. A_VFNMSUB132SS,
  1834. A_VFNMSUB213PD,
  1835. A_VFNMSUB213PS,
  1836. A_VFNMSUB213SD,
  1837. A_VFNMSUB213SS,
  1838. A_VFNMSUB231PD,
  1839. A_VFNMSUB231PS,
  1840. A_VFNMSUB231SD,
  1841. A_VFNMSUB231SS],[S_NO]) and
  1842. { we mix single and double opperations here because we assume that the compiler
  1843. generates vmovapd only after double operations and vmovaps only after single operations }
  1844. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1845. GetNextInstruction(hp1,hp2) and
  1846. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1847. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1848. begin
  1849. TransferUsedRegs(TmpUsedRegs);
  1850. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1851. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1852. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1853. begin
  1854. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1855. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1856. RemoveInstruction(hp2);
  1857. end;
  1858. end
  1859. else if (hp1.typ = ait_instruction) and
  1860. GetNextInstruction(hp1, hp2) and
  1861. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1862. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1863. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1864. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1865. (((taicpu(p).opcode=A_MOVAPS) and
  1866. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1867. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1868. ((taicpu(p).opcode=A_MOVAPD) and
  1869. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1870. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1871. ) then
  1872. { change
  1873. movapX reg,reg2
  1874. addsX/subsX/... reg3, reg2
  1875. movapX reg2,reg
  1876. to
  1877. addsX/subsX/... reg3,reg
  1878. }
  1879. begin
  1880. TransferUsedRegs(TmpUsedRegs);
  1881. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1882. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1883. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1884. begin
  1885. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1886. debug_op2str(taicpu(p).opcode)+' '+
  1887. debug_op2str(taicpu(hp1).opcode)+' '+
  1888. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1889. { we cannot eliminate the first move if
  1890. the operations uses the same register for source and dest }
  1891. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1892. RemoveCurrentP(p, nil);
  1893. p:=hp1;
  1894. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1895. RemoveInstruction(hp2);
  1896. result:=true;
  1897. end;
  1898. end;
  1899. end;
  1900. end;
  1901. end;
  1902. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1903. var
  1904. hp1 : tai;
  1905. begin
  1906. result:=false;
  1907. { replace
  1908. V<Op>X %mreg1,%mreg2,%mreg3
  1909. VMovX %mreg3,%mreg4
  1910. dealloc %mreg3
  1911. by
  1912. V<Op>X %mreg1,%mreg2,%mreg4
  1913. ?
  1914. }
  1915. if GetNextInstruction(p,hp1) and
  1916. { we mix single and double operations here because we assume that the compiler
  1917. generates vmovapd only after double operations and vmovaps only after single operations }
  1918. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1919. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1920. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1921. begin
  1922. TransferUsedRegs(TmpUsedRegs);
  1923. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1924. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1925. begin
  1926. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1927. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1928. RemoveInstruction(hp1);
  1929. result:=true;
  1930. end;
  1931. end;
  1932. end;
  1933. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1934. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1935. begin
  1936. Result := False;
  1937. { For safety reasons, only check for exact register matches }
  1938. { Check base register }
  1939. if (ref.base = AOldReg) then
  1940. begin
  1941. ref.base := ANewReg;
  1942. Result := True;
  1943. end;
  1944. { Check index register }
  1945. if (ref.index = AOldReg) then
  1946. begin
  1947. ref.index := ANewReg;
  1948. Result := True;
  1949. end;
  1950. end;
  1951. { Replaces all references to AOldReg in an operand to ANewReg }
  1952. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1953. var
  1954. OldSupReg, NewSupReg: TSuperRegister;
  1955. OldSubReg, NewSubReg: TSubRegister;
  1956. OldRegType: TRegisterType;
  1957. ThisOper: POper;
  1958. begin
  1959. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1960. Result := False;
  1961. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1962. InternalError(2020011801);
  1963. OldSupReg := getsupreg(AOldReg);
  1964. OldSubReg := getsubreg(AOldReg);
  1965. OldRegType := getregtype(AOldReg);
  1966. NewSupReg := getsupreg(ANewReg);
  1967. NewSubReg := getsubreg(ANewReg);
  1968. if OldRegType <> getregtype(ANewReg) then
  1969. InternalError(2020011802);
  1970. if OldSubReg <> NewSubReg then
  1971. InternalError(2020011803);
  1972. case ThisOper^.typ of
  1973. top_reg:
  1974. if (
  1975. (ThisOper^.reg = AOldReg) or
  1976. (
  1977. (OldRegType = R_INTREGISTER) and
  1978. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1979. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1980. (
  1981. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1982. {$ifndef x86_64}
  1983. and (
  1984. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1985. don't have an 8-bit representation }
  1986. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1987. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1988. )
  1989. {$endif x86_64}
  1990. )
  1991. )
  1992. ) then
  1993. begin
  1994. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  1995. Result := True;
  1996. end;
  1997. top_ref:
  1998. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  1999. Result := True;
  2000. else
  2001. ;
  2002. end;
  2003. end;
  2004. { Replaces all references to AOldReg in an instruction to ANewReg }
  2005. function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2006. const
  2007. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2008. var
  2009. OperIdx: Integer;
  2010. begin
  2011. Result := False;
  2012. for OperIdx := 0 to p.ops - 1 do
  2013. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) and
  2014. { The shift and rotate instructions can only use CL }
  2015. not (
  2016. (OperIdx = 0) and
  2017. { This second condition just helps to avoid unnecessarily
  2018. calling MatchInstruction for 10 different opcodes }
  2019. (p.oper[0]^.reg = NR_CL) and
  2020. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2021. ) then
  2022. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2023. end;
  2024. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean; inline;
  2025. begin
  2026. Result :=
  2027. (ref^.index = NR_NO) and
  2028. (
  2029. {$ifdef x86_64}
  2030. (
  2031. (ref^.base = NR_RIP) and
  2032. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2033. ) or
  2034. {$endif x86_64}
  2035. (ref^.base = NR_STACK_POINTER_REG) or
  2036. (ref^.base = current_procinfo.framepointer)
  2037. );
  2038. end;
  2039. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2040. var
  2041. l: asizeint;
  2042. begin
  2043. Result := False;
  2044. { Should have been checked previously }
  2045. if p.opcode <> A_LEA then
  2046. InternalError(2020072501);
  2047. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2048. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2049. not(cs_opt_size in current_settings.optimizerswitches) then
  2050. exit;
  2051. with p.oper[0]^.ref^ do
  2052. begin
  2053. if (base <> p.oper[1]^.reg) or
  2054. (index <> NR_NO) or
  2055. assigned(symbol) then
  2056. exit;
  2057. l:=offset;
  2058. if (l=1) and UseIncDec then
  2059. begin
  2060. p.opcode:=A_INC;
  2061. p.loadreg(0,p.oper[1]^.reg);
  2062. p.ops:=1;
  2063. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2064. end
  2065. else if (l=-1) and UseIncDec then
  2066. begin
  2067. p.opcode:=A_DEC;
  2068. p.loadreg(0,p.oper[1]^.reg);
  2069. p.ops:=1;
  2070. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2071. end
  2072. else
  2073. begin
  2074. if (l<0) and (l<>-2147483648) then
  2075. begin
  2076. p.opcode:=A_SUB;
  2077. p.loadConst(0,-l);
  2078. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2079. end
  2080. else
  2081. begin
  2082. p.opcode:=A_ADD;
  2083. p.loadConst(0,l);
  2084. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2085. end;
  2086. end;
  2087. end;
  2088. Result := True;
  2089. end;
  2090. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2091. var
  2092. CurrentReg, ReplaceReg: TRegister;
  2093. begin
  2094. Result := False;
  2095. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2096. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2097. case hp.opcode of
  2098. A_FSTSW, A_FNSTSW,
  2099. A_IN, A_INS, A_OUT, A_OUTS,
  2100. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2101. { These routines have explicit operands, but they are restricted in
  2102. what they can be (e.g. IN and OUT can only read from AL, AX or
  2103. EAX. }
  2104. Exit;
  2105. A_IMUL:
  2106. begin
  2107. { The 1-operand version writes to implicit registers
  2108. The 2-operand version reads from the first operator, and reads
  2109. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2110. the 3-operand version reads from a register that it doesn't write to
  2111. }
  2112. case hp.ops of
  2113. 1:
  2114. if (
  2115. (
  2116. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2117. ) or
  2118. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2119. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2120. begin
  2121. Result := True;
  2122. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2123. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2124. end;
  2125. 2:
  2126. { Only modify the first parameter }
  2127. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2128. begin
  2129. Result := True;
  2130. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2131. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2132. end;
  2133. 3:
  2134. { Only modify the second parameter }
  2135. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2136. begin
  2137. Result := True;
  2138. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2139. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2140. end;
  2141. else
  2142. InternalError(2020012901);
  2143. end;
  2144. end;
  2145. else
  2146. if (hp.ops > 0) and
  2147. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2148. begin
  2149. Result := True;
  2150. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2151. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2152. end;
  2153. end;
  2154. end;
  2155. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2156. var
  2157. hp1, hp2, hp3: tai;
  2158. DoOptimisation, TempBool: Boolean;
  2159. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2160. begin
  2161. if taicpu(hp1).opcode = signed_movop then
  2162. begin
  2163. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2164. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2165. end
  2166. else
  2167. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2168. end;
  2169. var
  2170. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2171. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2172. NewSize: topsize;
  2173. CurrentReg, ActiveReg: TRegister;
  2174. SourceRef, TargetRef: TReference;
  2175. MovAligned, MovUnaligned: TAsmOp;
  2176. begin
  2177. Result:=false;
  2178. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2179. { remove mov reg1,reg1? }
  2180. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2181. then
  2182. begin
  2183. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2184. { take care of the register (de)allocs following p }
  2185. RemoveCurrentP(p, hp1);
  2186. Result:=true;
  2187. exit;
  2188. end;
  2189. { All the next optimisations require a next instruction }
  2190. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2191. Exit;
  2192. { Look for:
  2193. mov %reg1,%reg2
  2194. ??? %reg2,r/m
  2195. Change to:
  2196. mov %reg1,%reg2
  2197. ??? %reg1,r/m
  2198. }
  2199. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2200. begin
  2201. CurrentReg := taicpu(p).oper[1]^.reg;
  2202. if RegReadByInstruction(CurrentReg, hp1) and
  2203. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2204. begin
  2205. TransferUsedRegs(TmpUsedRegs);
  2206. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2207. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2208. { Just in case something didn't get modified (e.g. an
  2209. implicit register) }
  2210. not RegReadByInstruction(CurrentReg, hp1) then
  2211. begin
  2212. { We can remove the original MOV }
  2213. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2214. RemoveCurrentp(p, hp1);
  2215. { UsedRegs got updated by RemoveCurrentp }
  2216. Result := True;
  2217. Exit;
  2218. end;
  2219. { If we know a MOV instruction has become a null operation, we might as well
  2220. get rid of it now to save time. }
  2221. if (taicpu(hp1).opcode = A_MOV) and
  2222. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2223. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2224. { Just being a register is enough to confirm it's a null operation }
  2225. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2226. begin
  2227. Result := True;
  2228. { Speed-up to reduce a pipeline stall... if we had something like...
  2229. movl %eax,%edx
  2230. movw %dx,%ax
  2231. ... the second instruction would change to movw %ax,%ax, but
  2232. given that it is now %ax that's active rather than %eax,
  2233. penalties might occur due to a partial register write, so instead,
  2234. change it to a MOVZX instruction when optimising for speed.
  2235. }
  2236. if not (cs_opt_size in current_settings.optimizerswitches) and
  2237. IsMOVZXAcceptable and
  2238. (taicpu(hp1).opsize < taicpu(p).opsize)
  2239. {$ifdef x86_64}
  2240. { operations already implicitly set the upper 64 bits to zero }
  2241. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2242. {$endif x86_64}
  2243. then
  2244. begin
  2245. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2246. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2247. case taicpu(p).opsize of
  2248. S_W:
  2249. if taicpu(hp1).opsize = S_B then
  2250. taicpu(hp1).opsize := S_BL
  2251. else
  2252. InternalError(2020012911);
  2253. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2254. case taicpu(hp1).opsize of
  2255. S_B:
  2256. taicpu(hp1).opsize := S_BL;
  2257. S_W:
  2258. taicpu(hp1).opsize := S_WL;
  2259. else
  2260. InternalError(2020012912);
  2261. end;
  2262. else
  2263. InternalError(2020012910);
  2264. end;
  2265. taicpu(hp1).opcode := A_MOVZX;
  2266. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2267. end
  2268. else
  2269. begin
  2270. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2271. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2272. RemoveInstruction(hp1);
  2273. { The instruction after what was hp1 is now the immediate next instruction,
  2274. so we can continue to make optimisations if it's present }
  2275. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2276. Exit;
  2277. hp1 := hp2;
  2278. end;
  2279. end;
  2280. end;
  2281. end;
  2282. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2283. overwrites the original destination register. e.g.
  2284. movl ###,%reg2d
  2285. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2286. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2287. }
  2288. if (taicpu(p).oper[1]^.typ = top_reg) and
  2289. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2290. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2291. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2292. begin
  2293. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2294. begin
  2295. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2296. case taicpu(p).oper[0]^.typ of
  2297. top_const:
  2298. { We have something like:
  2299. movb $x, %regb
  2300. movzbl %regb,%regd
  2301. Change to:
  2302. movl $x, %regd
  2303. }
  2304. begin
  2305. case taicpu(hp1).opsize of
  2306. S_BW:
  2307. begin
  2308. convert_mov_value(A_MOVSX, $FF);
  2309. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2310. taicpu(p).opsize := S_W;
  2311. end;
  2312. S_BL:
  2313. begin
  2314. convert_mov_value(A_MOVSX, $FF);
  2315. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2316. taicpu(p).opsize := S_L;
  2317. end;
  2318. S_WL:
  2319. begin
  2320. convert_mov_value(A_MOVSX, $FFFF);
  2321. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2322. taicpu(p).opsize := S_L;
  2323. end;
  2324. {$ifdef x86_64}
  2325. S_BQ:
  2326. begin
  2327. convert_mov_value(A_MOVSX, $FF);
  2328. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2329. taicpu(p).opsize := S_Q;
  2330. end;
  2331. S_WQ:
  2332. begin
  2333. convert_mov_value(A_MOVSX, $FFFF);
  2334. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2335. taicpu(p).opsize := S_Q;
  2336. end;
  2337. S_LQ:
  2338. begin
  2339. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2340. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2341. taicpu(p).opsize := S_Q;
  2342. end;
  2343. {$endif x86_64}
  2344. else
  2345. { If hp1 was a MOV instruction, it should have been
  2346. optimised already }
  2347. InternalError(2020021001);
  2348. end;
  2349. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2350. RemoveInstruction(hp1);
  2351. Result := True;
  2352. Exit;
  2353. end;
  2354. top_ref:
  2355. { We have something like:
  2356. movb mem, %regb
  2357. movzbl %regb,%regd
  2358. Change to:
  2359. movzbl mem, %regd
  2360. }
  2361. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2362. begin
  2363. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2364. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2365. RemoveCurrentP(p, hp1);
  2366. Result:=True;
  2367. Exit;
  2368. end;
  2369. else
  2370. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2371. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2372. Exit;
  2373. end;
  2374. end
  2375. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2376. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2377. optimised }
  2378. else
  2379. begin
  2380. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2381. RemoveCurrentP(p, hp1);
  2382. Result := True;
  2383. Exit;
  2384. end;
  2385. end;
  2386. if (taicpu(hp1).opcode = A_AND) and
  2387. (taicpu(p).oper[1]^.typ = top_reg) and
  2388. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2389. begin
  2390. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2391. begin
  2392. case taicpu(p).opsize of
  2393. S_L:
  2394. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2395. begin
  2396. { Optimize out:
  2397. mov x, %reg
  2398. and ffffffffh, %reg
  2399. }
  2400. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2401. RemoveInstruction(hp1);
  2402. Result:=true;
  2403. exit;
  2404. end;
  2405. S_Q: { TODO: Confirm if this is even possible }
  2406. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2407. begin
  2408. { Optimize out:
  2409. mov x, %reg
  2410. and ffffffffffffffffh, %reg
  2411. }
  2412. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2413. RemoveInstruction(hp1);
  2414. Result:=true;
  2415. exit;
  2416. end;
  2417. else
  2418. ;
  2419. end;
  2420. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2421. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2422. GetNextInstruction(hp1,hp2) and
  2423. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2424. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2425. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2426. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2427. GetNextInstruction(hp2,hp3) and
  2428. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2429. (taicpu(hp3).condition in [C_E,C_NE]) then
  2430. begin
  2431. TransferUsedRegs(TmpUsedRegs);
  2432. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2433. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2434. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2435. begin
  2436. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2437. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2438. taicpu(hp1).opcode:=A_TEST;
  2439. RemoveInstruction(hp2);
  2440. RemoveCurrentP(p, hp1);
  2441. Result:=true;
  2442. exit;
  2443. end;
  2444. end;
  2445. end
  2446. else if IsMOVZXAcceptable and
  2447. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2448. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2449. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2450. then
  2451. begin
  2452. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2453. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2454. case taicpu(p).opsize of
  2455. S_B:
  2456. if (taicpu(hp1).oper[0]^.val = $ff) then
  2457. begin
  2458. { Convert:
  2459. movb x, %regl movb x, %regl
  2460. andw ffh, %regw andl ffh, %regd
  2461. To:
  2462. movzbw x, %regd movzbl x, %regd
  2463. (Identical registers, just different sizes)
  2464. }
  2465. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2466. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2467. case taicpu(hp1).opsize of
  2468. S_W: NewSize := S_BW;
  2469. S_L: NewSize := S_BL;
  2470. {$ifdef x86_64}
  2471. S_Q: NewSize := S_BQ;
  2472. {$endif x86_64}
  2473. else
  2474. InternalError(2018011510);
  2475. end;
  2476. end
  2477. else
  2478. NewSize := S_NO;
  2479. S_W:
  2480. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2481. begin
  2482. { Convert:
  2483. movw x, %regw
  2484. andl ffffh, %regd
  2485. To:
  2486. movzwl x, %regd
  2487. (Identical registers, just different sizes)
  2488. }
  2489. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2490. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2491. case taicpu(hp1).opsize of
  2492. S_L: NewSize := S_WL;
  2493. {$ifdef x86_64}
  2494. S_Q: NewSize := S_WQ;
  2495. {$endif x86_64}
  2496. else
  2497. InternalError(2018011511);
  2498. end;
  2499. end
  2500. else
  2501. NewSize := S_NO;
  2502. else
  2503. NewSize := S_NO;
  2504. end;
  2505. if NewSize <> S_NO then
  2506. begin
  2507. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2508. { The actual optimization }
  2509. taicpu(p).opcode := A_MOVZX;
  2510. taicpu(p).changeopsize(NewSize);
  2511. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2512. { Safeguard if "and" is followed by a conditional command }
  2513. TransferUsedRegs(TmpUsedRegs);
  2514. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2515. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2516. begin
  2517. { At this point, the "and" command is effectively equivalent to
  2518. "test %reg,%reg". This will be handled separately by the
  2519. Peephole Optimizer. [Kit] }
  2520. DebugMsg(SPeepholeOptimization + PreMessage +
  2521. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2522. end
  2523. else
  2524. begin
  2525. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2526. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2527. RemoveInstruction(hp1);
  2528. end;
  2529. Result := True;
  2530. Exit;
  2531. end;
  2532. end;
  2533. end;
  2534. if (taicpu(hp1).opcode = A_OR) and
  2535. (taicpu(p).oper[1]^.typ = top_reg) and
  2536. MatchOperand(taicpu(p).oper[0]^, 0) and
  2537. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2538. begin
  2539. { mov 0, %reg
  2540. or ###,%reg
  2541. Change to (only if the flags are not used):
  2542. mov ###,%reg
  2543. }
  2544. TransferUsedRegs(TmpUsedRegs);
  2545. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2546. DoOptimisation := True;
  2547. { Even if the flags are used, we might be able to do the optimisation
  2548. if the conditions are predictable }
  2549. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2550. begin
  2551. { Only perform if ### = %reg (the same register) or equal to 0,
  2552. so %reg is guaranteed to still have a value of zero }
  2553. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2554. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2555. begin
  2556. hp2 := hp1;
  2557. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2558. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2559. GetNextInstruction(hp2, hp3) do
  2560. begin
  2561. { Don't continue modifying if the flags state is getting changed }
  2562. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2563. Break;
  2564. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2565. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2566. begin
  2567. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2568. begin
  2569. { Condition is always true }
  2570. case taicpu(hp3).opcode of
  2571. A_Jcc:
  2572. begin
  2573. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2574. { Check for jump shortcuts before we destroy the condition }
  2575. DoJumpOptimizations(hp3, TempBool);
  2576. MakeUnconditional(taicpu(hp3));
  2577. Result := True;
  2578. end;
  2579. A_CMOVcc:
  2580. begin
  2581. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2582. taicpu(hp3).opcode := A_MOV;
  2583. taicpu(hp3).condition := C_None;
  2584. Result := True;
  2585. end;
  2586. A_SETcc:
  2587. begin
  2588. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2589. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2590. taicpu(hp3).opcode := A_MOV;
  2591. taicpu(hp3).ops := 2;
  2592. taicpu(hp3).condition := C_None;
  2593. taicpu(hp3).opsize := S_B;
  2594. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2595. taicpu(hp3).loadconst(0, 1);
  2596. Result := True;
  2597. end;
  2598. else
  2599. InternalError(2021090701);
  2600. end;
  2601. end
  2602. else if (taicpu(hp3).condition in [C_A, C_B, C_C, C_G, C_L, C_NE, C_NZ, C_O, C_S]) then
  2603. begin
  2604. { Condition is always false }
  2605. case taicpu(hp3).opcode of
  2606. A_Jcc:
  2607. begin
  2608. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2609. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2610. RemoveInstruction(hp3);
  2611. Result := True;
  2612. { Since hp3 was deleted, hp2 must not be updated }
  2613. Continue;
  2614. end;
  2615. A_CMOVcc:
  2616. begin
  2617. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2618. RemoveInstruction(hp3);
  2619. Result := True;
  2620. { Since hp3 was deleted, hp2 must not be updated }
  2621. Continue;
  2622. end;
  2623. A_SETcc:
  2624. begin
  2625. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2626. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2627. taicpu(hp3).opcode := A_MOV;
  2628. taicpu(hp3).ops := 2;
  2629. taicpu(hp3).condition := C_None;
  2630. taicpu(hp3).opsize := S_B;
  2631. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2632. taicpu(hp3).loadconst(0, 0);
  2633. Result := True;
  2634. end;
  2635. else
  2636. InternalError(2021090702);
  2637. end;
  2638. end
  2639. else
  2640. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2641. DoOptimisation := False;
  2642. end;
  2643. hp2 := hp3;
  2644. end;
  2645. { Flags are still in use - don't optimise }
  2646. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2647. DoOptimisation := False;
  2648. end
  2649. else
  2650. DoOptimisation := False;
  2651. end;
  2652. if DoOptimisation then
  2653. begin
  2654. {$ifdef x86_64}
  2655. { OR only supports 32-bit sign-extended constants for 64-bit
  2656. instructions, so compensate for this if the constant is
  2657. encoded as a value greater than or equal to 2^31 }
  2658. if (taicpu(hp1).opsize = S_Q) and
  2659. (taicpu(hp1).oper[0]^.typ = top_const) and
  2660. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2661. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2662. {$endif x86_64}
  2663. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2664. taicpu(hp1).opcode := A_MOV;
  2665. RemoveCurrentP(p, hp1);
  2666. Result := True;
  2667. Exit;
  2668. end;
  2669. end;
  2670. { Next instruction is also a MOV ? }
  2671. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2672. begin
  2673. if (taicpu(p).oper[1]^.typ = top_reg) and
  2674. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2675. begin
  2676. CurrentReg := taicpu(p).oper[1]^.reg;
  2677. TransferUsedRegs(TmpUsedRegs);
  2678. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2679. { we have
  2680. mov x, %treg
  2681. mov %treg, y
  2682. }
  2683. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2684. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2685. { we've got
  2686. mov x, %treg
  2687. mov %treg, y
  2688. with %treg is not used after }
  2689. case taicpu(p).oper[0]^.typ Of
  2690. { top_reg is covered by DeepMOVOpt }
  2691. top_const:
  2692. begin
  2693. { change
  2694. mov const, %treg
  2695. mov %treg, y
  2696. to
  2697. mov const, y
  2698. }
  2699. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2700. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2701. begin
  2702. if taicpu(hp1).oper[1]^.typ=top_reg then
  2703. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2704. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2705. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2706. RemoveInstruction(hp1);
  2707. Result:=true;
  2708. Exit;
  2709. end;
  2710. end;
  2711. top_ref:
  2712. case taicpu(hp1).oper[1]^.typ of
  2713. top_reg:
  2714. begin
  2715. { change
  2716. mov mem, %treg
  2717. mov %treg, %reg
  2718. to
  2719. mov mem, %reg"
  2720. }
  2721. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2722. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2723. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2724. RemoveInstruction(hp1);
  2725. Result:=true;
  2726. Exit;
  2727. end;
  2728. top_ref:
  2729. begin
  2730. {$ifdef x86_64}
  2731. { Look for the following to simplify:
  2732. mov x(mem1), %reg
  2733. mov %reg, y(mem2)
  2734. mov x+8(mem1), %reg
  2735. mov %reg, y+8(mem2)
  2736. Change to:
  2737. movdqu x(mem1), %xmmreg
  2738. movdqu %xmmreg, y(mem2)
  2739. }
  2740. SourceRef := taicpu(p).oper[0]^.ref^;
  2741. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2742. if (taicpu(p).opsize = S_Q) and
  2743. GetNextInstruction(hp1, hp2) and
  2744. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2745. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2746. begin
  2747. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2748. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2749. Inc(SourceRef.offset, 8);
  2750. if UseAVX then
  2751. begin
  2752. MovAligned := A_VMOVDQA;
  2753. MovUnaligned := A_VMOVDQU;
  2754. end
  2755. else
  2756. begin
  2757. MovAligned := A_MOVDQA;
  2758. MovUnaligned := A_MOVDQU;
  2759. end;
  2760. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2761. begin
  2762. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2763. Inc(TargetRef.offset, 8);
  2764. if GetNextInstruction(hp2, hp3) and
  2765. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2766. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2767. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2768. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2769. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2770. begin
  2771. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2772. if CurrentReg <> NR_NO then
  2773. begin
  2774. { Remember that the offsets are 8 ahead }
  2775. if ((SourceRef.offset mod 16) = 8) and
  2776. (
  2777. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2778. (SourceRef.base = current_procinfo.framepointer) or
  2779. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2780. ) then
  2781. taicpu(p).opcode := MovAligned
  2782. else
  2783. taicpu(p).opcode := MovUnaligned;
  2784. taicpu(p).opsize := S_XMM;
  2785. taicpu(p).oper[1]^.reg := CurrentReg;
  2786. if ((TargetRef.offset mod 16) = 8) and
  2787. (
  2788. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2789. (TargetRef.base = current_procinfo.framepointer) or
  2790. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2791. ) then
  2792. taicpu(hp1).opcode := MovAligned
  2793. else
  2794. taicpu(hp1).opcode := MovUnaligned;
  2795. taicpu(hp1).opsize := S_XMM;
  2796. taicpu(hp1).oper[0]^.reg := CurrentReg;
  2797. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  2798. RemoveInstruction(hp2);
  2799. RemoveInstruction(hp3);
  2800. Result := True;
  2801. Exit;
  2802. end;
  2803. end;
  2804. end
  2805. else
  2806. begin
  2807. { See if the next references are 8 less rather than 8 greater }
  2808. Dec(SourceRef.offset, 16); { -8 the other way }
  2809. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2810. begin
  2811. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2812. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  2813. if GetNextInstruction(hp2, hp3) and
  2814. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2815. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2816. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2817. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2818. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2819. begin
  2820. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2821. if CurrentReg <> NR_NO then
  2822. begin
  2823. { hp2 and hp3 are the starting offsets, so mod 0 this time }
  2824. if ((SourceRef.offset mod 16) = 0) and
  2825. (
  2826. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2827. (SourceRef.base = current_procinfo.framepointer) or
  2828. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2829. ) then
  2830. taicpu(hp2).opcode := MovAligned
  2831. else
  2832. taicpu(hp2).opcode := MovUnaligned;
  2833. taicpu(hp2).opsize := S_XMM;
  2834. taicpu(hp2).oper[1]^.reg := CurrentReg;
  2835. if ((TargetRef.offset mod 16) = 0) and
  2836. (
  2837. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2838. (TargetRef.base = current_procinfo.framepointer) or
  2839. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2840. ) then
  2841. taicpu(hp3).opcode := MovAligned
  2842. else
  2843. taicpu(hp3).opcode := MovUnaligned;
  2844. taicpu(hp3).opsize := S_XMM;
  2845. taicpu(hp3).oper[0]^.reg := CurrentReg;
  2846. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  2847. RemoveInstruction(hp1);
  2848. RemoveCurrentP(p, hp2);
  2849. Result := True;
  2850. Exit;
  2851. end;
  2852. end;
  2853. end;
  2854. end;
  2855. end;
  2856. {$endif x86_64}
  2857. end;
  2858. else
  2859. { The write target should be a reg or a ref }
  2860. InternalError(2021091601);
  2861. end;
  2862. else
  2863. ;
  2864. end
  2865. else
  2866. { %treg is used afterwards, but all eventualities
  2867. other than the first MOV instruction being a constant
  2868. are covered by DeepMOVOpt, so only check for that }
  2869. if (taicpu(p).oper[0]^.typ = top_const) and
  2870. (
  2871. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2872. not (cs_opt_size in current_settings.optimizerswitches) or
  2873. (taicpu(hp1).opsize = S_B)
  2874. ) and
  2875. (
  2876. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2877. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2878. ) then
  2879. begin
  2880. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2881. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2882. end;
  2883. end;
  2884. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2885. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2886. { mov reg1, mem1 or mov mem1, reg1
  2887. mov mem2, reg2 mov reg2, mem2}
  2888. begin
  2889. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2890. { mov reg1, mem1 or mov mem1, reg1
  2891. mov mem2, reg1 mov reg2, mem1}
  2892. begin
  2893. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2894. { Removes the second statement from
  2895. mov reg1, mem1/reg2
  2896. mov mem1/reg2, reg1 }
  2897. begin
  2898. if taicpu(p).oper[0]^.typ=top_reg then
  2899. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2900. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2901. RemoveInstruction(hp1);
  2902. Result:=true;
  2903. exit;
  2904. end
  2905. else
  2906. begin
  2907. TransferUsedRegs(TmpUsedRegs);
  2908. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2909. if (taicpu(p).oper[1]^.typ = top_ref) and
  2910. { mov reg1, mem1
  2911. mov mem2, reg1 }
  2912. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2913. GetNextInstruction(hp1, hp2) and
  2914. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2915. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2916. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2917. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2918. { change to
  2919. mov reg1, mem1 mov reg1, mem1
  2920. mov mem2, reg1 cmp reg1, mem2
  2921. cmp mem1, reg1
  2922. }
  2923. begin
  2924. RemoveInstruction(hp2);
  2925. taicpu(hp1).opcode := A_CMP;
  2926. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2927. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2928. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2929. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2930. end;
  2931. end;
  2932. end
  2933. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2934. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2935. begin
  2936. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2937. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2938. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2939. end
  2940. else
  2941. begin
  2942. TransferUsedRegs(TmpUsedRegs);
  2943. if GetNextInstruction(hp1, hp2) and
  2944. MatchOpType(taicpu(p),top_ref,top_reg) and
  2945. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2946. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2947. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2948. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2949. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2950. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2951. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2952. { mov mem1, %reg1
  2953. mov %reg1, mem2
  2954. mov mem2, reg2
  2955. to:
  2956. mov mem1, reg2
  2957. mov reg2, mem2}
  2958. begin
  2959. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2960. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2961. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2962. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2963. RemoveInstruction(hp2);
  2964. Result := True;
  2965. end
  2966. {$ifdef i386}
  2967. { this is enabled for i386 only, as the rules to create the reg sets below
  2968. are too complicated for x86-64, so this makes this code too error prone
  2969. on x86-64
  2970. }
  2971. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2972. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2973. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2974. { mov mem1, reg1 mov mem1, reg1
  2975. mov reg1, mem2 mov reg1, mem2
  2976. mov mem2, reg2 mov mem2, reg1
  2977. to: to:
  2978. mov mem1, reg1 mov mem1, reg1
  2979. mov mem1, reg2 mov reg1, mem2
  2980. mov reg1, mem2
  2981. or (if mem1 depends on reg1
  2982. and/or if mem2 depends on reg2)
  2983. to:
  2984. mov mem1, reg1
  2985. mov reg1, mem2
  2986. mov reg1, reg2
  2987. }
  2988. begin
  2989. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  2990. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  2991. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  2992. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  2993. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2994. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  2995. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2996. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  2997. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  2998. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2999. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3000. end
  3001. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3002. begin
  3003. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3004. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3005. end
  3006. else
  3007. begin
  3008. RemoveInstruction(hp2);
  3009. end
  3010. {$endif i386}
  3011. ;
  3012. end;
  3013. end
  3014. { movl [mem1],reg1
  3015. movl [mem1],reg2
  3016. to
  3017. movl [mem1],reg1
  3018. movl reg1,reg2
  3019. }
  3020. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3021. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3022. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3023. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3024. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3025. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3026. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3027. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3028. begin
  3029. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3030. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3031. end;
  3032. { movl const1,[mem1]
  3033. movl [mem1],reg1
  3034. to
  3035. movl const1,reg1
  3036. movl reg1,[mem1]
  3037. }
  3038. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3039. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3040. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3041. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3042. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3043. begin
  3044. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3045. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3046. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3047. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3048. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3049. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3050. Result:=true;
  3051. exit;
  3052. end;
  3053. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3054. end;
  3055. { search further than the next instruction for a mov (as long as it's not a jump) }
  3056. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3057. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3058. (taicpu(p).oper[1]^.typ = top_reg) and
  3059. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3060. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3061. begin
  3062. { we work with hp2 here, so hp1 can be still used later on when
  3063. checking for GetNextInstruction_p }
  3064. hp3 := hp1;
  3065. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3066. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3067. { Saves on a large number of dereferences }
  3068. ActiveReg := taicpu(p).oper[1]^.reg;
  3069. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3070. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3071. (hp2.typ=ait_instruction) do
  3072. begin
  3073. case taicpu(hp2).opcode of
  3074. A_MOV:
  3075. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3076. ((taicpu(p).oper[0]^.typ=top_const) or
  3077. ((taicpu(p).oper[0]^.typ=top_reg) and
  3078. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3079. )
  3080. ) then
  3081. begin
  3082. { we have
  3083. mov x, %treg
  3084. mov %treg, y
  3085. }
  3086. TransferUsedRegs(TmpUsedRegs);
  3087. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  3088. { We don't need to call UpdateUsedRegs for every instruction between
  3089. p and hp2 because the register we're concerned about will not
  3090. become deallocated (otherwise GetNextInstructionUsingReg would
  3091. have stopped at an earlier instruction). [Kit] }
  3092. TempRegUsed :=
  3093. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3094. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) or
  3095. RegReadByInstruction(ActiveReg, hp1);
  3096. case taicpu(p).oper[0]^.typ Of
  3097. top_reg:
  3098. begin
  3099. { change
  3100. mov %reg, %treg
  3101. mov %treg, y
  3102. to
  3103. mov %reg, y
  3104. }
  3105. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3106. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3107. if taicpu(hp2).oper[1]^.reg = CurrentReg then
  3108. begin
  3109. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3110. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3111. if TempRegUsed then
  3112. begin
  3113. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3114. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3115. { Set the start of the next GetNextInstructionUsingRegCond search
  3116. to start at the entry right before hp2 (which is about to be removed) }
  3117. hp3 := tai(hp2.Previous);
  3118. RemoveInstruction(hp2);
  3119. { See if there's more we can optimise }
  3120. Continue;
  3121. end
  3122. else
  3123. begin
  3124. RemoveInstruction(hp2);
  3125. { We can remove the original MOV too }
  3126. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3127. RemoveCurrentP(p, hp1);
  3128. Result:=true;
  3129. Exit;
  3130. end;
  3131. end
  3132. else
  3133. begin
  3134. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3135. taicpu(hp2).loadReg(0, CurrentReg);
  3136. if TempRegUsed then
  3137. begin
  3138. { Don't remove the first instruction if the temporary register is in use }
  3139. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3140. { No need to set Result to True. If there's another instruction later on
  3141. that can be optimised, it will be detected when the main Pass 1 loop
  3142. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3143. end
  3144. else
  3145. begin
  3146. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3147. RemoveCurrentP(p, hp1);
  3148. Result:=true;
  3149. Exit;
  3150. end;
  3151. end;
  3152. end;
  3153. top_const:
  3154. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3155. begin
  3156. { change
  3157. mov const, %treg
  3158. mov %treg, y
  3159. to
  3160. mov const, y
  3161. }
  3162. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3163. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3164. begin
  3165. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3166. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3167. if TempRegUsed then
  3168. begin
  3169. { Don't remove the first instruction if the temporary register is in use }
  3170. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3171. { No need to set Result to True. If there's another instruction later on
  3172. that can be optimised, it will be detected when the main Pass 1 loop
  3173. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3174. end
  3175. else
  3176. begin
  3177. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3178. RemoveCurrentP(p, hp1);
  3179. Result:=true;
  3180. Exit;
  3181. end;
  3182. end;
  3183. end;
  3184. else
  3185. Internalerror(2019103001);
  3186. end;
  3187. end
  3188. else
  3189. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3190. begin
  3191. if not CrossJump and
  3192. not RegUsedBetween(ActiveReg, p, hp2) and
  3193. not RegReadByInstruction(ActiveReg, hp2) then
  3194. begin
  3195. { Register is not used before it is overwritten }
  3196. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3197. RemoveCurrentp(p, hp1);
  3198. Result := True;
  3199. Exit;
  3200. end;
  3201. if (taicpu(p).oper[0]^.typ = top_const) and
  3202. (taicpu(hp2).oper[0]^.typ = top_const) then
  3203. begin
  3204. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3205. begin
  3206. { Same value - register hasn't changed }
  3207. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3208. RemoveInstruction(hp2);
  3209. Result := True;
  3210. { See if there's more we can optimise }
  3211. Continue;
  3212. end;
  3213. end;
  3214. end;
  3215. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3216. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3217. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3218. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3219. begin
  3220. {
  3221. Change from:
  3222. mov ###, %reg
  3223. ...
  3224. movs/z %reg,%reg (Same register, just different sizes)
  3225. To:
  3226. movs/z ###, %reg (Longer version)
  3227. ...
  3228. (remove)
  3229. }
  3230. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3231. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3232. { Keep the first instruction as mov if ### is a constant }
  3233. if taicpu(p).oper[0]^.typ = top_const then
  3234. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3235. else
  3236. begin
  3237. taicpu(p).opcode := taicpu(hp2).opcode;
  3238. taicpu(p).opsize := taicpu(hp2).opsize;
  3239. end;
  3240. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3241. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3242. RemoveInstruction(hp2);
  3243. Result := True;
  3244. Exit;
  3245. end;
  3246. else
  3247. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3248. begin
  3249. TransferUsedRegs(TmpUsedRegs);
  3250. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  3251. if
  3252. not RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) and
  3253. not RegModifiedBetween(taicpu(p).oper[0]^.reg, hp1, hp2) and
  3254. DeepMovOpt(taicpu(p), taicpu(hp2)) then
  3255. begin
  3256. { Just in case something didn't get modified (e.g. an
  3257. implicit register) }
  3258. if not RegReadByInstruction(ActiveReg, hp2) and
  3259. { If a conditional jump was crossed, do not delete
  3260. the original MOV no matter what }
  3261. not CrossJump then
  3262. begin
  3263. TransferUsedRegs(TmpUsedRegs);
  3264. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3265. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3266. if
  3267. { Make sure the original register isn't still present
  3268. and has been written to (e.g. with SHRX) }
  3269. RegLoadedWithNewValue(ActiveReg, hp2) or
  3270. not RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) then
  3271. begin
  3272. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3273. { We can remove the original MOV }
  3274. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3275. RemoveCurrentp(p, hp1);
  3276. Result := True;
  3277. Exit;
  3278. end
  3279. else
  3280. begin
  3281. { See if there's more we can optimise }
  3282. hp3 := hp2;
  3283. Continue;
  3284. end;
  3285. end;
  3286. end;
  3287. end;
  3288. end;
  3289. { Break out of the while loop under normal circumstances }
  3290. Break;
  3291. end;
  3292. end;
  3293. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3294. (taicpu(p).oper[1]^.typ = top_reg) and
  3295. (taicpu(p).opsize = S_L) and
  3296. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3297. (taicpu(hp2).opcode = A_AND) and
  3298. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3299. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3300. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3301. ) then
  3302. begin
  3303. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3304. begin
  3305. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3306. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3307. begin
  3308. { Optimize out:
  3309. mov x, %reg
  3310. and ffffffffh, %reg
  3311. }
  3312. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3313. RemoveInstruction(hp2);
  3314. Result:=true;
  3315. exit;
  3316. end;
  3317. end;
  3318. end;
  3319. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3320. x >= RetOffset) as it doesn't do anything (it writes either to a
  3321. parameter or to the temporary storage room for the function
  3322. result)
  3323. }
  3324. if IsExitCode(hp1) and
  3325. (taicpu(p).oper[1]^.typ = top_ref) and
  3326. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3327. (
  3328. (
  3329. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3330. not (
  3331. assigned(current_procinfo.procdef.funcretsym) and
  3332. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3333. )
  3334. ) or
  3335. { Also discard writes to the stack that are below the base pointer,
  3336. as this is temporary storage rather than a function result on the
  3337. stack, say. }
  3338. (
  3339. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3340. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3341. )
  3342. ) then
  3343. begin
  3344. RemoveCurrentp(p, hp1);
  3345. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3346. RemoveLastDeallocForFuncRes(p);
  3347. Result:=true;
  3348. exit;
  3349. end;
  3350. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3351. begin
  3352. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3353. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3354. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3355. begin
  3356. { change
  3357. mov reg1, mem1
  3358. test/cmp x, mem1
  3359. to
  3360. mov reg1, mem1
  3361. test/cmp x, reg1
  3362. }
  3363. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3364. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3365. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3366. Result := True;
  3367. Exit;
  3368. end;
  3369. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3370. { The x86 assemblers have difficulty comparing values against absolute addresses }
  3371. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  3372. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  3373. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  3374. (
  3375. (
  3376. (taicpu(hp1).opcode = A_TEST)
  3377. ) or (
  3378. (taicpu(hp1).opcode = A_CMP) and
  3379. { A sanity check more than anything }
  3380. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  3381. )
  3382. ) then
  3383. begin
  3384. { change
  3385. mov mem, %reg
  3386. cmp/test x, %reg / test %reg,%reg
  3387. (reg deallocated)
  3388. to
  3389. cmp/test x, mem / cmp 0, mem
  3390. }
  3391. TransferUsedRegs(TmpUsedRegs);
  3392. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3393. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3394. begin
  3395. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  3396. if (taicpu(hp1).opcode = A_TEST) and
  3397. (
  3398. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  3399. MatchOperand(taicpu(hp1).oper[0]^, -1)
  3400. ) then
  3401. begin
  3402. taicpu(hp1).opcode := A_CMP;
  3403. taicpu(hp1).loadconst(0, 0);
  3404. end;
  3405. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  3406. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  3407. RemoveCurrentP(p, hp1);
  3408. Result := True;
  3409. Exit;
  3410. end;
  3411. end;
  3412. end;
  3413. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3414. { If the flags register is in use, don't change the instruction to an
  3415. ADD otherwise this will scramble the flags. [Kit] }
  3416. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3417. begin
  3418. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3419. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3420. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3421. ) or
  3422. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3423. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3424. )
  3425. ) then
  3426. { mov reg1,ref
  3427. lea reg2,[reg1,reg2]
  3428. to
  3429. add reg2,ref}
  3430. begin
  3431. TransferUsedRegs(TmpUsedRegs);
  3432. { reg1 may not be used afterwards }
  3433. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3434. begin
  3435. Taicpu(hp1).opcode:=A_ADD;
  3436. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3437. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3438. RemoveCurrentp(p, hp1);
  3439. result:=true;
  3440. exit;
  3441. end;
  3442. end;
  3443. { If the LEA instruction can be converted into an arithmetic instruction,
  3444. it may be possible to then fold it in the next optimisation, otherwise
  3445. there's nothing more that can be optimised here. }
  3446. if not ConvertLEA(taicpu(hp1)) then
  3447. Exit;
  3448. end;
  3449. if (taicpu(p).oper[1]^.typ = top_reg) and
  3450. (hp1.typ = ait_instruction) and
  3451. GetNextInstruction(hp1, hp2) and
  3452. MatchInstruction(hp2,A_MOV,[]) and
  3453. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3454. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3455. (
  3456. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3457. {$ifdef x86_64}
  3458. or
  3459. (
  3460. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3461. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3462. )
  3463. {$endif x86_64}
  3464. ) then
  3465. begin
  3466. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3467. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3468. { change movsX/movzX reg/ref, reg2
  3469. add/sub/or/... reg3/$const, reg2
  3470. mov reg2 reg/ref
  3471. dealloc reg2
  3472. to
  3473. add/sub/or/... reg3/$const, reg/ref }
  3474. begin
  3475. TransferUsedRegs(TmpUsedRegs);
  3476. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3477. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3478. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3479. begin
  3480. { by example:
  3481. movswl %si,%eax movswl %si,%eax p
  3482. decl %eax addl %edx,%eax hp1
  3483. movw %ax,%si movw %ax,%si hp2
  3484. ->
  3485. movswl %si,%eax movswl %si,%eax p
  3486. decw %eax addw %edx,%eax hp1
  3487. movw %ax,%si movw %ax,%si hp2
  3488. }
  3489. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3490. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3491. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3492. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3493. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3494. {
  3495. ->
  3496. movswl %si,%eax movswl %si,%eax p
  3497. decw %si addw %dx,%si hp1
  3498. movw %ax,%si movw %ax,%si hp2
  3499. }
  3500. case taicpu(hp1).ops of
  3501. 1:
  3502. begin
  3503. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3504. if taicpu(hp1).oper[0]^.typ=top_reg then
  3505. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3506. end;
  3507. 2:
  3508. begin
  3509. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3510. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3511. (taicpu(hp1).opcode<>A_SHL) and
  3512. (taicpu(hp1).opcode<>A_SHR) and
  3513. (taicpu(hp1).opcode<>A_SAR) then
  3514. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3515. end;
  3516. else
  3517. internalerror(2008042701);
  3518. end;
  3519. {
  3520. ->
  3521. decw %si addw %dx,%si p
  3522. }
  3523. RemoveInstruction(hp2);
  3524. RemoveCurrentP(p, hp1);
  3525. Result:=True;
  3526. Exit;
  3527. end;
  3528. end;
  3529. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3530. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3531. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3532. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3533. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3534. )
  3535. {$ifdef i386}
  3536. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3537. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3538. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3539. {$endif i386}
  3540. then
  3541. { change movsX/movzX reg/ref, reg2
  3542. add/sub/or/... regX/$const, reg2
  3543. mov reg2, reg3
  3544. dealloc reg2
  3545. to
  3546. movsX/movzX reg/ref, reg3
  3547. add/sub/or/... reg3/$const, reg3
  3548. }
  3549. begin
  3550. TransferUsedRegs(TmpUsedRegs);
  3551. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3552. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3553. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3554. begin
  3555. { by example:
  3556. movswl %si,%eax movswl %si,%eax p
  3557. decl %eax addl %edx,%eax hp1
  3558. movw %ax,%si movw %ax,%si hp2
  3559. ->
  3560. movswl %si,%eax movswl %si,%eax p
  3561. decw %eax addw %edx,%eax hp1
  3562. movw %ax,%si movw %ax,%si hp2
  3563. }
  3564. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3565. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3566. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3567. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3568. { limit size of constants as well to avoid assembler errors, but
  3569. check opsize to avoid overflow when left shifting the 1 }
  3570. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3571. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3572. {$ifdef x86_64}
  3573. { Be careful of, for example:
  3574. movl %reg1,%reg2
  3575. addl %reg3,%reg2
  3576. movq %reg2,%reg4
  3577. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3578. }
  3579. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3580. begin
  3581. taicpu(hp2).changeopsize(S_L);
  3582. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3583. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3584. end;
  3585. {$endif x86_64}
  3586. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3587. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3588. if taicpu(p).oper[0]^.typ=top_reg then
  3589. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3590. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3591. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3592. {
  3593. ->
  3594. movswl %si,%eax movswl %si,%eax p
  3595. decw %si addw %dx,%si hp1
  3596. movw %ax,%si movw %ax,%si hp2
  3597. }
  3598. case taicpu(hp1).ops of
  3599. 1:
  3600. begin
  3601. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3602. if taicpu(hp1).oper[0]^.typ=top_reg then
  3603. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3604. end;
  3605. 2:
  3606. begin
  3607. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3608. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3609. (taicpu(hp1).opcode<>A_SHL) and
  3610. (taicpu(hp1).opcode<>A_SHR) and
  3611. (taicpu(hp1).opcode<>A_SAR) then
  3612. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3613. end;
  3614. else
  3615. internalerror(2018111801);
  3616. end;
  3617. {
  3618. ->
  3619. decw %si addw %dx,%si p
  3620. }
  3621. RemoveInstruction(hp2);
  3622. end;
  3623. end;
  3624. end;
  3625. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3626. GetNextInstruction(hp1, hp2) and
  3627. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3628. MatchOperand(Taicpu(p).oper[0]^,0) and
  3629. (Taicpu(p).oper[1]^.typ = top_reg) and
  3630. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3631. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3632. { mov reg1,0
  3633. bts reg1,operand1 --> mov reg1,operand2
  3634. or reg1,operand2 bts reg1,operand1}
  3635. begin
  3636. Taicpu(hp2).opcode:=A_MOV;
  3637. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3638. asml.remove(hp1);
  3639. insertllitem(hp2,hp2.next,hp1);
  3640. RemoveCurrentp(p, hp1);
  3641. Result:=true;
  3642. exit;
  3643. end;
  3644. {
  3645. mov ref,reg0
  3646. <op> reg0,reg1
  3647. dealloc reg0
  3648. to
  3649. <op> ref,reg1
  3650. }
  3651. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3652. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3653. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3654. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3655. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3656. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3657. begin
  3658. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3659. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3660. RemoveCurrentp(p, hp1);
  3661. Result:=true;
  3662. exit;
  3663. end;
  3664. {$ifdef x86_64}
  3665. { Convert:
  3666. movq x(ref),%reg64
  3667. shrq y,%reg64
  3668. To:
  3669. movq x+4(ref),%reg32
  3670. shrq y-32,%reg32 (Remove if y = 32)
  3671. }
  3672. if (taicpu(p).opsize = S_Q) and
  3673. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3674. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3675. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3676. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3677. (taicpu(hp1).oper[0]^.val >= 32) and
  3678. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3679. begin
  3680. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3681. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3682. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3683. { Convert to 32-bit }
  3684. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3685. taicpu(p).opsize := S_L;
  3686. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3687. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3688. if (taicpu(hp1).oper[0]^.val = 32) then
  3689. begin
  3690. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3691. RemoveInstruction(hp1);
  3692. end
  3693. else
  3694. begin
  3695. { This will potentially open up more arithmetic operations since
  3696. the peephole optimizer now has a big hint that only the lower
  3697. 32 bits are currently in use (and opcodes are smaller in size) }
  3698. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3699. taicpu(hp1).opsize := S_L;
  3700. Dec(taicpu(hp1).oper[0]^.val, 32);
  3701. DebugMsg(SPeepholeOptimization + PreMessage +
  3702. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3703. end;
  3704. Result := True;
  3705. Exit;
  3706. end;
  3707. {$endif x86_64}
  3708. end;
  3709. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3710. var
  3711. hp1 : tai;
  3712. begin
  3713. Result:=false;
  3714. if taicpu(p).ops <> 2 then
  3715. exit;
  3716. if GetNextInstruction(p,hp1) and
  3717. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3718. (taicpu(hp1).ops = 2) then
  3719. begin
  3720. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3721. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3722. { movXX reg1, mem1 or movXX mem1, reg1
  3723. movXX mem2, reg2 movXX reg2, mem2}
  3724. begin
  3725. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3726. { movXX reg1, mem1 or movXX mem1, reg1
  3727. movXX mem2, reg1 movXX reg2, mem1}
  3728. begin
  3729. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3730. begin
  3731. { Removes the second statement from
  3732. movXX reg1, mem1/reg2
  3733. movXX mem1/reg2, reg1
  3734. }
  3735. if taicpu(p).oper[0]^.typ=top_reg then
  3736. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3737. { Removes the second statement from
  3738. movXX mem1/reg1, reg2
  3739. movXX reg2, mem1/reg1
  3740. }
  3741. if (taicpu(p).oper[1]^.typ=top_reg) and
  3742. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3743. begin
  3744. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3745. RemoveInstruction(hp1);
  3746. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3747. end
  3748. else
  3749. begin
  3750. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3751. RemoveInstruction(hp1);
  3752. end;
  3753. Result:=true;
  3754. exit;
  3755. end
  3756. end;
  3757. end;
  3758. end;
  3759. end;
  3760. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3761. var
  3762. hp1 : tai;
  3763. begin
  3764. result:=false;
  3765. { replace
  3766. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3767. MovX %mreg2,%mreg1
  3768. dealloc %mreg2
  3769. by
  3770. <Op>X %mreg2,%mreg1
  3771. ?
  3772. }
  3773. if GetNextInstruction(p,hp1) and
  3774. { we mix single and double opperations here because we assume that the compiler
  3775. generates vmovapd only after double operations and vmovaps only after single operations }
  3776. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3777. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3778. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3779. (taicpu(p).oper[0]^.typ=top_reg) then
  3780. begin
  3781. TransferUsedRegs(TmpUsedRegs);
  3782. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3783. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3784. begin
  3785. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3786. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3787. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3788. RemoveInstruction(hp1);
  3789. result:=true;
  3790. end;
  3791. end;
  3792. end;
  3793. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3794. var
  3795. hp1, p_label, p_dist, hp1_dist: tai;
  3796. JumpLabel, JumpLabel_dist: TAsmLabel;
  3797. begin
  3798. Result := False;
  3799. if GetNextInstruction(p, hp1) and
  3800. MatchInstruction(hp1,A_MOV,[]) and
  3801. (
  3802. (taicpu(p).oper[0]^.typ <> top_reg) or
  3803. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  3804. ) and
  3805. (
  3806. (taicpu(p).oper[1]^.typ <> top_reg) or
  3807. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  3808. ) and
  3809. (
  3810. { Make sure the register written to doesn't appear in the
  3811. test instruction (in a reference, say) }
  3812. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3813. not RegInInstruction(taicpu(hp1).oper[1]^.reg, p)
  3814. ) then
  3815. begin
  3816. { If we have something like:
  3817. test %reg1,%reg1
  3818. mov 0,%reg2
  3819. And no registers are shared (the two %reg1's can be different, as
  3820. long as neither of them are also %reg2), move the MOV command to
  3821. before the comparison as this means it can be optimised without
  3822. worrying about the FLAGS register. (This combination is generated
  3823. by "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  3824. }
  3825. SwapMovCmp(p, hp1);
  3826. Result := True;
  3827. Exit;
  3828. end;
  3829. { Search for:
  3830. test %reg,%reg
  3831. j(c1) @lbl1
  3832. ...
  3833. @lbl:
  3834. test %reg,%reg (same register)
  3835. j(c2) @lbl2
  3836. If c2 is a subset of c1, change to:
  3837. test %reg,%reg
  3838. j(c1) @lbl2
  3839. (@lbl1 may become a dead label as a result)
  3840. }
  3841. if (taicpu(p).oper[1]^.typ = top_reg) and
  3842. (taicpu(p).oper[0]^.typ = top_reg) and
  3843. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  3844. MatchInstruction(hp1, A_JCC, []) and
  3845. IsJumpToLabel(taicpu(hp1)) then
  3846. begin
  3847. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  3848. p_label := nil;
  3849. if Assigned(JumpLabel) then
  3850. p_label := getlabelwithsym(JumpLabel);
  3851. if Assigned(p_label) and
  3852. GetNextInstruction(p_label, p_dist) and
  3853. MatchInstruction(p_dist, A_TEST, []) and
  3854. { It's fine if the second test uses smaller sub-registers }
  3855. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  3856. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  3857. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  3858. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  3859. GetNextInstruction(p_dist, hp1_dist) and
  3860. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  3861. begin
  3862. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  3863. if JumpLabel = JumpLabel_dist then
  3864. { This is an infinite loop }
  3865. Exit;
  3866. { Best optimisation when the first condition is a subset (or equal) of the second }
  3867. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  3868. begin
  3869. { Any registers used here will already be allocated }
  3870. if Assigned(JumpLabel_dist) then
  3871. JumpLabel_dist.IncRefs;
  3872. if Assigned(JumpLabel) then
  3873. JumpLabel.DecRefs;
  3874. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  3875. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  3876. Result := True;
  3877. Exit;
  3878. end;
  3879. end;
  3880. end;
  3881. end;
  3882. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  3883. var
  3884. hp1 : tai;
  3885. begin
  3886. result:=false;
  3887. { replace
  3888. addX const,%reg1
  3889. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  3890. dealloc %reg1
  3891. by
  3892. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  3893. }
  3894. if MatchOpType(taicpu(p),top_const,top_reg) and
  3895. GetNextInstruction(p,hp1) and
  3896. MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3897. ((taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base) or
  3898. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index)) then
  3899. begin
  3900. TransferUsedRegs(TmpUsedRegs);
  3901. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3902. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3903. begin
  3904. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  3905. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base then
  3906. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  3907. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index then
  3908. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3909. RemoveCurrentP(p);
  3910. result:=true;
  3911. end;
  3912. end;
  3913. end;
  3914. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  3915. var
  3916. hp1: tai;
  3917. ref: Integer;
  3918. saveref: treference;
  3919. TempReg: TRegister;
  3920. Multiple: TCGInt;
  3921. begin
  3922. Result:=false;
  3923. { removes seg register prefixes from LEA operations, as they
  3924. don't do anything}
  3925. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  3926. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  3927. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3928. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  3929. (
  3930. { do not mess with leas accessing the stack pointer
  3931. unless it's a null operation }
  3932. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  3933. (
  3934. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  3935. (taicpu(p).oper[0]^.ref^.offset = 0)
  3936. )
  3937. ) and
  3938. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  3939. begin
  3940. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  3941. begin
  3942. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  3943. begin
  3944. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  3945. taicpu(p).oper[1]^.reg);
  3946. InsertLLItem(p.previous,p.next, hp1);
  3947. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  3948. p.free;
  3949. p:=hp1;
  3950. end
  3951. else
  3952. begin
  3953. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  3954. RemoveCurrentP(p);
  3955. end;
  3956. Result:=true;
  3957. exit;
  3958. end
  3959. else if (
  3960. { continue to use lea to adjust the stack pointer,
  3961. it is the recommended way, but only if not optimizing for size }
  3962. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  3963. (cs_opt_size in current_settings.optimizerswitches)
  3964. ) and
  3965. { If the flags register is in use, don't change the instruction
  3966. to an ADD otherwise this will scramble the flags. [Kit] }
  3967. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  3968. ConvertLEA(taicpu(p)) then
  3969. begin
  3970. Result:=true;
  3971. exit;
  3972. end;
  3973. end;
  3974. if GetNextInstruction(p,hp1) and
  3975. (hp1.typ=ait_instruction) then
  3976. begin
  3977. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  3978. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3979. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  3980. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  3981. begin
  3982. TransferUsedRegs(TmpUsedRegs);
  3983. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3984. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3985. begin
  3986. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3987. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  3988. RemoveInstruction(hp1);
  3989. result:=true;
  3990. exit;
  3991. end;
  3992. end;
  3993. { changes
  3994. lea <ref1>, reg1
  3995. <op> ...,<ref. with reg1>,...
  3996. to
  3997. <op> ...,<ref1>,... }
  3998. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  3999. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4000. not(MatchInstruction(hp1,A_LEA,[])) then
  4001. begin
  4002. { find a reference which uses reg1 }
  4003. 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
  4004. ref:=0
  4005. 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
  4006. ref:=1
  4007. else
  4008. ref:=-1;
  4009. if (ref<>-1) and
  4010. { reg1 must be either the base or the index }
  4011. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4012. begin
  4013. { reg1 can be removed from the reference }
  4014. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4015. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4016. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4017. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4018. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4019. else
  4020. Internalerror(2019111201);
  4021. { check if the can insert all data of the lea into the second instruction }
  4022. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4023. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4024. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4025. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4026. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4027. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4028. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4029. {$ifdef x86_64}
  4030. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4031. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4032. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4033. )
  4034. {$endif x86_64}
  4035. then
  4036. begin
  4037. { reg1 might not used by the second instruction after it is remove from the reference }
  4038. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4039. begin
  4040. TransferUsedRegs(TmpUsedRegs);
  4041. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4042. { reg1 is not updated so it might not be used afterwards }
  4043. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4044. begin
  4045. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4046. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4047. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4048. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4049. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4050. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4051. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4052. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4053. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4054. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4055. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4056. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4057. RemoveCurrentP(p, hp1);
  4058. result:=true;
  4059. exit;
  4060. end
  4061. end;
  4062. end;
  4063. { recover }
  4064. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4065. end;
  4066. end;
  4067. end;
  4068. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4069. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4070. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4071. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4072. begin
  4073. { Check common LEA/LEA conditions }
  4074. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4075. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4076. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4077. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  4078. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4079. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4080. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  4081. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4082. (
  4083. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4084. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4085. ) and (
  4086. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4087. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4088. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4089. ) then
  4090. begin
  4091. { changes
  4092. lea (regX,scale), reg1
  4093. lea offset(reg1,reg1), reg1
  4094. to
  4095. lea offset(regX,scale*2), reg1
  4096. and
  4097. lea (regX,scale1), reg1
  4098. lea offset(reg1,scale2), reg1
  4099. to
  4100. lea offset(regX,scale1*scale2), reg1
  4101. ... so long as the final scale does not exceed 8
  4102. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4103. }
  4104. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4105. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4106. (
  4107. (
  4108. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4109. ) or (
  4110. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4111. (
  4112. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4113. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4114. )
  4115. )
  4116. ) and (
  4117. (
  4118. { lea (reg1,scale2), reg1 variant }
  4119. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4120. (
  4121. (
  4122. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4123. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4124. ) or (
  4125. { lea (regX,regX), reg1 variant }
  4126. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4127. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4128. )
  4129. )
  4130. ) or (
  4131. { lea (reg1,reg1), reg1 variant }
  4132. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4133. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4134. )
  4135. ) then
  4136. begin
  4137. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4138. { Make everything homogeneous to make calculations easier }
  4139. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4140. begin
  4141. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4142. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4143. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4144. else
  4145. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4146. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4147. end;
  4148. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4149. begin
  4150. { Just to prevent miscalculations }
  4151. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4152. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4153. else
  4154. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4155. end
  4156. else
  4157. begin
  4158. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4159. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4160. end;
  4161. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4162. RemoveCurrentP(p);
  4163. result:=true;
  4164. exit;
  4165. end
  4166. { changes
  4167. lea offset1(regX), reg1
  4168. lea offset2(reg1), reg1
  4169. to
  4170. lea offset1+offset2(regX), reg1 }
  4171. else if
  4172. (
  4173. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4174. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4175. ) or (
  4176. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4177. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4178. (
  4179. (
  4180. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4181. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4182. ) or (
  4183. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4184. (
  4185. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4186. (
  4187. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4188. (
  4189. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4190. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4191. )
  4192. )
  4193. )
  4194. )
  4195. )
  4196. ) then
  4197. begin
  4198. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4199. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4200. begin
  4201. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4202. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4203. { if the register is used as index and base, we have to increase for base as well
  4204. and adapt base }
  4205. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4206. begin
  4207. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4208. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4209. end;
  4210. end
  4211. else
  4212. begin
  4213. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4214. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4215. end;
  4216. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4217. begin
  4218. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4219. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4220. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4221. end;
  4222. RemoveCurrentP(p);
  4223. result:=true;
  4224. exit;
  4225. end;
  4226. end;
  4227. { Change:
  4228. leal/q $x(%reg1),%reg2
  4229. ...
  4230. shll/q $y,%reg2
  4231. To:
  4232. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4233. }
  4234. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4235. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4236. (taicpu(hp1).oper[0]^.val <= 3) then
  4237. begin
  4238. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4239. TransferUsedRegs(TmpUsedRegs);
  4240. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4241. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4242. if
  4243. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4244. (this works even if scalefactor is zero) }
  4245. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4246. { Ensure offset doesn't go out of bounds }
  4247. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4248. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4249. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4250. (
  4251. (
  4252. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4253. (
  4254. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4255. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4256. (
  4257. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4258. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4259. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4260. )
  4261. )
  4262. ) or (
  4263. (
  4264. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4265. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4266. ) and
  4267. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4268. )
  4269. ) then
  4270. begin
  4271. repeat
  4272. with taicpu(p).oper[0]^.ref^ do
  4273. begin
  4274. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4275. if index = base then
  4276. begin
  4277. if Multiple > 4 then
  4278. { Optimisation will no longer work because resultant
  4279. scale factor will exceed 8 }
  4280. Break;
  4281. base := NR_NO;
  4282. scalefactor := 2;
  4283. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4284. end
  4285. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4286. begin
  4287. { Scale factor only works on the index register }
  4288. index := base;
  4289. base := NR_NO;
  4290. end;
  4291. { For safety }
  4292. if scalefactor <= 1 then
  4293. begin
  4294. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4295. scalefactor := Multiple;
  4296. end
  4297. else
  4298. begin
  4299. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4300. scalefactor := scalefactor * Multiple;
  4301. end;
  4302. offset := offset * Multiple;
  4303. end;
  4304. RemoveInstruction(hp1);
  4305. Result := True;
  4306. Exit;
  4307. { This repeat..until loop exists for the benefit of Break }
  4308. until True;
  4309. end;
  4310. end;
  4311. end;
  4312. end;
  4313. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4314. var
  4315. hp1 : tai;
  4316. begin
  4317. DoSubAddOpt := False;
  4318. if GetLastInstruction(p, hp1) and
  4319. (hp1.typ = ait_instruction) and
  4320. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4321. case taicpu(hp1).opcode Of
  4322. A_DEC:
  4323. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  4324. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4325. begin
  4326. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4327. RemoveInstruction(hp1);
  4328. end;
  4329. A_SUB:
  4330. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  4331. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4332. begin
  4333. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4334. RemoveInstruction(hp1);
  4335. end;
  4336. A_ADD:
  4337. begin
  4338. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  4339. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4340. begin
  4341. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4342. RemoveInstruction(hp1);
  4343. if (taicpu(p).oper[0]^.val = 0) then
  4344. begin
  4345. hp1 := tai(p.next);
  4346. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4347. if not GetLastInstruction(hp1, p) then
  4348. p := hp1;
  4349. DoSubAddOpt := True;
  4350. end
  4351. end;
  4352. end;
  4353. else
  4354. ;
  4355. end;
  4356. end;
  4357. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4358. {$ifdef i386}
  4359. var
  4360. hp1 : tai;
  4361. {$endif i386}
  4362. begin
  4363. Result:=false;
  4364. { * change "subl $2, %esp; pushw x" to "pushl x"}
  4365. { * change "sub/add const1, reg" or "dec reg" followed by
  4366. "sub const2, reg" to one "sub ..., reg" }
  4367. if MatchOpType(taicpu(p),top_const,top_reg) then
  4368. begin
  4369. {$ifdef i386}
  4370. if (taicpu(p).oper[0]^.val = 2) and
  4371. (taicpu(p).oper[1]^.reg = NR_ESP) and
  4372. { Don't do the sub/push optimization if the sub }
  4373. { comes from setting up the stack frame (JM) }
  4374. (not(GetLastInstruction(p,hp1)) or
  4375. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  4376. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  4377. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  4378. begin
  4379. hp1 := tai(p.next);
  4380. while Assigned(hp1) and
  4381. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  4382. not RegReadByInstruction(NR_ESP,hp1) and
  4383. not RegModifiedByInstruction(NR_ESP,hp1) do
  4384. hp1 := tai(hp1.next);
  4385. if Assigned(hp1) and
  4386. MatchInstruction(hp1,A_PUSH,[S_W]) then
  4387. begin
  4388. taicpu(hp1).changeopsize(S_L);
  4389. if taicpu(hp1).oper[0]^.typ=top_reg then
  4390. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  4391. hp1 := tai(p.next);
  4392. RemoveCurrentp(p, hp1);
  4393. Result:=true;
  4394. exit;
  4395. end;
  4396. end;
  4397. {$endif i386}
  4398. if DoSubAddOpt(p) then
  4399. Result:=true;
  4400. end;
  4401. end;
  4402. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  4403. var
  4404. TmpBool1,TmpBool2 : Boolean;
  4405. tmpref : treference;
  4406. hp1,hp2: tai;
  4407. mask: tcgint;
  4408. begin
  4409. Result:=false;
  4410. { All these optimisations work on "shl/sal const,%reg" }
  4411. if not MatchOpType(taicpu(p),top_const,top_reg) then
  4412. Exit;
  4413. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4414. (taicpu(p).oper[0]^.val <= 3) then
  4415. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  4416. begin
  4417. { should we check the next instruction? }
  4418. TmpBool1 := True;
  4419. { have we found an add/sub which could be
  4420. integrated in the lea? }
  4421. TmpBool2 := False;
  4422. reference_reset(tmpref,2,[]);
  4423. TmpRef.index := taicpu(p).oper[1]^.reg;
  4424. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4425. while TmpBool1 and
  4426. GetNextInstruction(p, hp1) and
  4427. (tai(hp1).typ = ait_instruction) and
  4428. ((((taicpu(hp1).opcode = A_ADD) or
  4429. (taicpu(hp1).opcode = A_SUB)) and
  4430. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  4431. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  4432. (((taicpu(hp1).opcode = A_INC) or
  4433. (taicpu(hp1).opcode = A_DEC)) and
  4434. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4435. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  4436. ((taicpu(hp1).opcode = A_LEA) and
  4437. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4438. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  4439. (not GetNextInstruction(hp1,hp2) or
  4440. not instrReadsFlags(hp2)) Do
  4441. begin
  4442. TmpBool1 := False;
  4443. if taicpu(hp1).opcode=A_LEA then
  4444. begin
  4445. if (TmpRef.base = NR_NO) and
  4446. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  4447. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  4448. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  4449. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  4450. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  4451. begin
  4452. TmpBool1 := True;
  4453. TmpBool2 := True;
  4454. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  4455. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  4456. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  4457. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  4458. RemoveInstruction(hp1);
  4459. end
  4460. end
  4461. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  4462. begin
  4463. TmpBool1 := True;
  4464. TmpBool2 := True;
  4465. case taicpu(hp1).opcode of
  4466. A_ADD:
  4467. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4468. A_SUB:
  4469. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4470. else
  4471. internalerror(2019050536);
  4472. end;
  4473. RemoveInstruction(hp1);
  4474. end
  4475. else
  4476. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4477. (((taicpu(hp1).opcode = A_ADD) and
  4478. (TmpRef.base = NR_NO)) or
  4479. (taicpu(hp1).opcode = A_INC) or
  4480. (taicpu(hp1).opcode = A_DEC)) then
  4481. begin
  4482. TmpBool1 := True;
  4483. TmpBool2 := True;
  4484. case taicpu(hp1).opcode of
  4485. A_ADD:
  4486. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  4487. A_INC:
  4488. inc(TmpRef.offset);
  4489. A_DEC:
  4490. dec(TmpRef.offset);
  4491. else
  4492. internalerror(2019050535);
  4493. end;
  4494. RemoveInstruction(hp1);
  4495. end;
  4496. end;
  4497. if TmpBool2
  4498. {$ifndef x86_64}
  4499. or
  4500. ((current_settings.optimizecputype < cpu_Pentium2) and
  4501. (taicpu(p).oper[0]^.val <= 3) and
  4502. not(cs_opt_size in current_settings.optimizerswitches))
  4503. {$endif x86_64}
  4504. then
  4505. begin
  4506. if not(TmpBool2) and
  4507. (taicpu(p).oper[0]^.val=1) then
  4508. begin
  4509. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4510. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  4511. end
  4512. else
  4513. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  4514. taicpu(p).oper[1]^.reg);
  4515. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  4516. InsertLLItem(p.previous, p.next, hp1);
  4517. p.free;
  4518. p := hp1;
  4519. end;
  4520. end
  4521. {$ifndef x86_64}
  4522. else if (current_settings.optimizecputype < cpu_Pentium2) then
  4523. begin
  4524. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  4525. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  4526. (unlike shl, which is only Tairable in the U pipe) }
  4527. if taicpu(p).oper[0]^.val=1 then
  4528. begin
  4529. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4530. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  4531. InsertLLItem(p.previous, p.next, hp1);
  4532. p.free;
  4533. p := hp1;
  4534. end
  4535. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  4536. "shl $3, %reg" to "lea (,%reg,8), %reg }
  4537. else if (taicpu(p).opsize = S_L) and
  4538. (taicpu(p).oper[0]^.val<= 3) then
  4539. begin
  4540. reference_reset(tmpref,2,[]);
  4541. TmpRef.index := taicpu(p).oper[1]^.reg;
  4542. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4543. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  4544. InsertLLItem(p.previous, p.next, hp1);
  4545. p.free;
  4546. p := hp1;
  4547. end;
  4548. end
  4549. {$endif x86_64}
  4550. else if
  4551. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  4552. (
  4553. (
  4554. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  4555. SetAndTest(hp1, hp2)
  4556. {$ifdef x86_64}
  4557. ) or
  4558. (
  4559. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4560. GetNextInstruction(hp1, hp2) and
  4561. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  4562. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4563. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  4564. {$endif x86_64}
  4565. )
  4566. ) and
  4567. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  4568. begin
  4569. { Change:
  4570. shl x, %reg1
  4571. mov -(1<<x), %reg2
  4572. and %reg2, %reg1
  4573. Or:
  4574. shl x, %reg1
  4575. and -(1<<x), %reg1
  4576. To just:
  4577. shl x, %reg1
  4578. Since the and operation only zeroes bits that are already zero from the shl operation
  4579. }
  4580. case taicpu(p).oper[0]^.val of
  4581. 8:
  4582. mask:=$FFFFFFFFFFFFFF00;
  4583. 16:
  4584. mask:=$FFFFFFFFFFFF0000;
  4585. 32:
  4586. mask:=$FFFFFFFF00000000;
  4587. 63:
  4588. { Constant pre-calculated to prevent overflow errors with Int64 }
  4589. mask:=$8000000000000000;
  4590. else
  4591. begin
  4592. if taicpu(p).oper[0]^.val >= 64 then
  4593. { Shouldn't happen realistically, since the register
  4594. is guaranteed to be set to zero at this point }
  4595. mask := 0
  4596. else
  4597. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  4598. end;
  4599. end;
  4600. if taicpu(hp1).oper[0]^.val = mask then
  4601. begin
  4602. { Everything checks out, perform the optimisation, as long as
  4603. the FLAGS register isn't being used}
  4604. TransferUsedRegs(TmpUsedRegs);
  4605. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4606. {$ifdef x86_64}
  4607. if (hp1 <> hp2) then
  4608. begin
  4609. { "shl/mov/and" version }
  4610. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4611. { Don't do the optimisation if the FLAGS register is in use }
  4612. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  4613. begin
  4614. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  4615. { Don't remove the 'mov' instruction if its register is used elsewhere }
  4616. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  4617. begin
  4618. RemoveInstruction(hp1);
  4619. Result := True;
  4620. end;
  4621. { Only set Result to True if the 'mov' instruction was removed }
  4622. RemoveInstruction(hp2);
  4623. end;
  4624. end
  4625. else
  4626. {$endif x86_64}
  4627. begin
  4628. { "shl/and" version }
  4629. { Don't do the optimisation if the FLAGS register is in use }
  4630. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  4631. begin
  4632. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  4633. RemoveInstruction(hp1);
  4634. Result := True;
  4635. end;
  4636. end;
  4637. Exit;
  4638. end
  4639. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  4640. begin
  4641. { Even if the mask doesn't allow for its removal, we might be
  4642. able to optimise the mask for the "shl/and" version, which
  4643. may permit other peephole optimisations }
  4644. {$ifdef DEBUG_AOPTCPU}
  4645. mask := taicpu(hp1).oper[0]^.val and mask;
  4646. if taicpu(hp1).oper[0]^.val <> mask then
  4647. begin
  4648. DebugMsg(
  4649. SPeepholeOptimization +
  4650. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  4651. ' to $' + debug_tostr(mask) +
  4652. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  4653. taicpu(hp1).oper[0]^.val := mask;
  4654. end;
  4655. {$else DEBUG_AOPTCPU}
  4656. { If debugging is off, just set the operand even if it's the same }
  4657. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  4658. {$endif DEBUG_AOPTCPU}
  4659. end;
  4660. end;
  4661. {
  4662. change
  4663. shl/sal const,reg
  4664. <op> ...(...,reg,1),...
  4665. into
  4666. <op> ...(...,reg,1 shl const),...
  4667. if const in 1..3
  4668. }
  4669. if MatchOpType(taicpu(p), top_const, top_reg) and
  4670. (taicpu(p).oper[0]^.val in [1..3]) and
  4671. GetNextInstruction(p, hp1) and
  4672. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  4673. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  4674. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  4675. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  4676. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  4677. begin
  4678. TransferUsedRegs(TmpUsedRegs);
  4679. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4680. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4681. begin
  4682. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  4683. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  4684. RemoveCurrentP(p);
  4685. Result:=true;
  4686. end;
  4687. end;
  4688. end;
  4689. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  4690. var
  4691. CurrentRef: TReference;
  4692. FullReg: TRegister;
  4693. hp1, hp2: tai;
  4694. begin
  4695. Result := False;
  4696. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  4697. Exit;
  4698. { We assume you've checked if the operand is actually a reference by
  4699. this point. If it isn't, you'll most likely get an access violation }
  4700. CurrentRef := first_mov.oper[1]^.ref^;
  4701. { Memory must be aligned }
  4702. if (CurrentRef.offset mod 4) <> 0 then
  4703. Exit;
  4704. Inc(CurrentRef.offset);
  4705. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4706. if MatchOperand(second_mov.oper[0]^, 0) and
  4707. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  4708. GetNextInstruction(second_mov, hp1) and
  4709. (hp1.typ = ait_instruction) and
  4710. (taicpu(hp1).opcode = A_MOV) and
  4711. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4712. (taicpu(hp1).oper[0]^.val = 0) then
  4713. begin
  4714. Inc(CurrentRef.offset);
  4715. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  4716. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  4717. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  4718. begin
  4719. case taicpu(hp1).opsize of
  4720. S_B:
  4721. if GetNextInstruction(hp1, hp2) and
  4722. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  4723. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4724. (taicpu(hp2).oper[0]^.val = 0) then
  4725. begin
  4726. Inc(CurrentRef.offset);
  4727. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4728. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  4729. (taicpu(hp2).opsize = S_B) then
  4730. begin
  4731. RemoveInstruction(hp1);
  4732. RemoveInstruction(hp2);
  4733. first_mov.opsize := S_L;
  4734. if first_mov.oper[0]^.typ = top_reg then
  4735. begin
  4736. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  4737. { Reuse second_mov as a MOVZX instruction }
  4738. second_mov.opcode := A_MOVZX;
  4739. second_mov.opsize := S_BL;
  4740. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4741. second_mov.loadreg(1, FullReg);
  4742. first_mov.oper[0]^.reg := FullReg;
  4743. asml.Remove(second_mov);
  4744. asml.InsertBefore(second_mov, first_mov);
  4745. end
  4746. else
  4747. { It's a value }
  4748. begin
  4749. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  4750. RemoveInstruction(second_mov);
  4751. end;
  4752. Result := True;
  4753. Exit;
  4754. end;
  4755. end;
  4756. S_W:
  4757. begin
  4758. RemoveInstruction(hp1);
  4759. first_mov.opsize := S_L;
  4760. if first_mov.oper[0]^.typ = top_reg then
  4761. begin
  4762. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  4763. { Reuse second_mov as a MOVZX instruction }
  4764. second_mov.opcode := A_MOVZX;
  4765. second_mov.opsize := S_BL;
  4766. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4767. second_mov.loadreg(1, FullReg);
  4768. first_mov.oper[0]^.reg := FullReg;
  4769. asml.Remove(second_mov);
  4770. asml.InsertBefore(second_mov, first_mov);
  4771. end
  4772. else
  4773. { It's a value }
  4774. begin
  4775. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  4776. RemoveInstruction(second_mov);
  4777. end;
  4778. Result := True;
  4779. Exit;
  4780. end;
  4781. else
  4782. ;
  4783. end;
  4784. end;
  4785. end;
  4786. end;
  4787. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  4788. { returns true if a "continue" should be done after this optimization }
  4789. var
  4790. hp1, hp2: tai;
  4791. begin
  4792. Result := false;
  4793. if MatchOpType(taicpu(p),top_ref) and
  4794. GetNextInstruction(p, hp1) and
  4795. (hp1.typ = ait_instruction) and
  4796. (((taicpu(hp1).opcode = A_FLD) and
  4797. (taicpu(p).opcode = A_FSTP)) or
  4798. ((taicpu(p).opcode = A_FISTP) and
  4799. (taicpu(hp1).opcode = A_FILD))) and
  4800. MatchOpType(taicpu(hp1),top_ref) and
  4801. (taicpu(hp1).opsize = taicpu(p).opsize) and
  4802. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4803. begin
  4804. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  4805. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  4806. GetNextInstruction(hp1, hp2) and
  4807. (hp2.typ = ait_instruction) and
  4808. IsExitCode(hp2) and
  4809. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  4810. not(assigned(current_procinfo.procdef.funcretsym) and
  4811. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  4812. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  4813. begin
  4814. RemoveInstruction(hp1);
  4815. RemoveCurrentP(p, hp2);
  4816. RemoveLastDeallocForFuncRes(p);
  4817. Result := true;
  4818. end
  4819. else
  4820. { we can do this only in fast math mode as fstp is rounding ...
  4821. ... still disabled as it breaks the compiler and/or rtl }
  4822. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  4823. { ... or if another fstp equal to the first one follows }
  4824. (GetNextInstruction(hp1,hp2) and
  4825. (hp2.typ = ait_instruction) and
  4826. (taicpu(p).opcode=taicpu(hp2).opcode) and
  4827. (taicpu(p).opsize=taicpu(hp2).opsize))
  4828. ) and
  4829. { fst can't store an extended/comp value }
  4830. (taicpu(p).opsize <> S_FX) and
  4831. (taicpu(p).opsize <> S_IQ) then
  4832. begin
  4833. if (taicpu(p).opcode = A_FSTP) then
  4834. taicpu(p).opcode := A_FST
  4835. else
  4836. taicpu(p).opcode := A_FIST;
  4837. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  4838. RemoveInstruction(hp1);
  4839. end;
  4840. end;
  4841. end;
  4842. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  4843. var
  4844. hp1, hp2: tai;
  4845. begin
  4846. result:=false;
  4847. if MatchOpType(taicpu(p),top_reg) and
  4848. GetNextInstruction(p, hp1) and
  4849. (hp1.typ = Ait_Instruction) and
  4850. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4851. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  4852. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  4853. { change to
  4854. fld reg fxxx reg,st
  4855. fxxxp st, st1 (hp1)
  4856. Remark: non commutative operations must be reversed!
  4857. }
  4858. begin
  4859. case taicpu(hp1).opcode Of
  4860. A_FMULP,A_FADDP,
  4861. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4862. begin
  4863. case taicpu(hp1).opcode Of
  4864. A_FADDP: taicpu(hp1).opcode := A_FADD;
  4865. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  4866. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  4867. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  4868. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  4869. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  4870. else
  4871. internalerror(2019050534);
  4872. end;
  4873. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  4874. taicpu(hp1).oper[1]^.reg := NR_ST;
  4875. RemoveCurrentP(p, hp1);
  4876. Result:=true;
  4877. exit;
  4878. end;
  4879. else
  4880. ;
  4881. end;
  4882. end
  4883. else
  4884. if MatchOpType(taicpu(p),top_ref) and
  4885. GetNextInstruction(p, hp2) and
  4886. (hp2.typ = Ait_Instruction) and
  4887. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4888. (taicpu(p).opsize in [S_FS, S_FL]) and
  4889. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  4890. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  4891. if GetLastInstruction(p, hp1) and
  4892. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  4893. MatchOpType(taicpu(hp1),top_ref) and
  4894. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4895. if ((taicpu(hp2).opcode = A_FMULP) or
  4896. (taicpu(hp2).opcode = A_FADDP)) then
  4897. { change to
  4898. fld/fst mem1 (hp1) fld/fst mem1
  4899. fld mem1 (p) fadd/
  4900. faddp/ fmul st, st
  4901. fmulp st, st1 (hp2) }
  4902. begin
  4903. RemoveCurrentP(p, hp1);
  4904. if (taicpu(hp2).opcode = A_FADDP) then
  4905. taicpu(hp2).opcode := A_FADD
  4906. else
  4907. taicpu(hp2).opcode := A_FMUL;
  4908. taicpu(hp2).oper[1]^.reg := NR_ST;
  4909. end
  4910. else
  4911. { change to
  4912. fld/fst mem1 (hp1) fld/fst mem1
  4913. fld mem1 (p) fld st}
  4914. begin
  4915. taicpu(p).changeopsize(S_FL);
  4916. taicpu(p).loadreg(0,NR_ST);
  4917. end
  4918. else
  4919. begin
  4920. case taicpu(hp2).opcode Of
  4921. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4922. { change to
  4923. fld/fst mem1 (hp1) fld/fst mem1
  4924. fld mem2 (p) fxxx mem2
  4925. fxxxp st, st1 (hp2) }
  4926. begin
  4927. case taicpu(hp2).opcode Of
  4928. A_FADDP: taicpu(p).opcode := A_FADD;
  4929. A_FMULP: taicpu(p).opcode := A_FMUL;
  4930. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  4931. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  4932. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  4933. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  4934. else
  4935. internalerror(2019050533);
  4936. end;
  4937. RemoveInstruction(hp2);
  4938. end
  4939. else
  4940. ;
  4941. end
  4942. end
  4943. end;
  4944. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  4945. begin
  4946. Result := condition_in(cond1, cond2) or
  4947. { Not strictly subsets due to the actual flags checked, but because we're
  4948. comparing integers, E is a subset of AE and GE and their aliases }
  4949. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  4950. end;
  4951. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  4952. var
  4953. v: TCGInt;
  4954. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  4955. FirstMatch: Boolean;
  4956. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  4957. begin
  4958. Result:=false;
  4959. { All these optimisations need a next instruction }
  4960. if not GetNextInstruction(p, hp1) then
  4961. Exit;
  4962. { Search for:
  4963. cmp ###,###
  4964. j(c1) @lbl1
  4965. ...
  4966. @lbl:
  4967. cmp ###.### (same comparison as above)
  4968. j(c2) @lbl2
  4969. If c1 is a subset of c2, change to:
  4970. cmp ###,###
  4971. j(c2) @lbl2
  4972. (@lbl1 may become a dead label as a result)
  4973. }
  4974. { Also handle cases where there are multiple jumps in a row }
  4975. p_jump := hp1;
  4976. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  4977. begin
  4978. if IsJumpToLabel(taicpu(p_jump)) then
  4979. begin
  4980. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  4981. p_label := nil;
  4982. if Assigned(JumpLabel) then
  4983. p_label := getlabelwithsym(JumpLabel);
  4984. if Assigned(p_label) and
  4985. GetNextInstruction(p_label, p_dist) and
  4986. MatchInstruction(p_dist, A_CMP, []) and
  4987. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  4988. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4989. GetNextInstruction(p_dist, hp1_dist) and
  4990. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4991. begin
  4992. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4993. if JumpLabel = JumpLabel_dist then
  4994. { This is an infinite loop }
  4995. Exit;
  4996. { Best optimisation when the first condition is a subset (or equal) of the second }
  4997. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  4998. begin
  4999. { Any registers used here will already be allocated }
  5000. if Assigned(JumpLabel_dist) then
  5001. JumpLabel_dist.IncRefs;
  5002. if Assigned(JumpLabel) then
  5003. JumpLabel.DecRefs;
  5004. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5005. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5006. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5007. Result := True;
  5008. { Don't exit yet. Since p and p_jump haven't actually been
  5009. removed, we can check for more on this iteration }
  5010. end
  5011. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5012. GetNextInstruction(hp1_dist, hp1_label) and
  5013. SkipAligns(hp1_label, hp1_label) and
  5014. (hp1_label.typ = ait_label) then
  5015. begin
  5016. JumpLabel_far := tai_label(hp1_label).labsym;
  5017. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5018. { This is an infinite loop }
  5019. Exit;
  5020. if Assigned(JumpLabel_far) then
  5021. begin
  5022. { In this situation, if the first jump branches, the second one will never,
  5023. branch so change the destination label to after the second jump }
  5024. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5025. if Assigned(JumpLabel) then
  5026. JumpLabel.DecRefs;
  5027. JumpLabel_far.IncRefs;
  5028. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5029. Result := True;
  5030. { Don't exit yet. Since p and p_jump haven't actually been
  5031. removed, we can check for more on this iteration }
  5032. Continue;
  5033. end;
  5034. end;
  5035. end;
  5036. end;
  5037. { Search for:
  5038. cmp ###,###
  5039. j(c1) @lbl1
  5040. cmp ###,### (same as first)
  5041. Remove second cmp
  5042. }
  5043. if GetNextInstruction(p_jump, hp2) and
  5044. (
  5045. (
  5046. MatchInstruction(hp2, A_CMP, []) and
  5047. (
  5048. (
  5049. MatchOpType(taicpu(p), top_const, top_reg) and
  5050. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5051. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  5052. ) or (
  5053. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5054. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5055. )
  5056. )
  5057. ) or (
  5058. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5059. MatchOperand(taicpu(p).oper[0]^, 0) and
  5060. (taicpu(p).oper[1]^.typ = top_reg) and
  5061. MatchInstruction(hp2, A_TEST, []) and
  5062. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5063. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5064. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  5065. )
  5066. ) then
  5067. begin
  5068. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5069. RemoveInstruction(hp2);
  5070. Result := True;
  5071. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5072. end;
  5073. GetNextInstruction(p_jump, p_jump);
  5074. end;
  5075. if taicpu(p).oper[0]^.typ = top_const then
  5076. begin
  5077. if (taicpu(p).oper[0]^.val = 0) and
  5078. (taicpu(p).oper[1]^.typ = top_reg) and
  5079. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  5080. begin
  5081. hp2 := p;
  5082. FirstMatch := True;
  5083. { When dealing with "cmp $0,%reg", only ZF and SF contain
  5084. anything meaningful once it's converted to "test %reg,%reg";
  5085. additionally, some jumps will always (or never) branch, so
  5086. evaluate every jump immediately following the
  5087. comparison, optimising the conditions if possible.
  5088. Similarly with SETcc... those that are always set to 0 or 1
  5089. are changed to MOV instructions }
  5090. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  5091. (
  5092. GetNextInstruction(hp2, hp1) and
  5093. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  5094. ) do
  5095. begin
  5096. FirstMatch := False;
  5097. case taicpu(hp1).condition of
  5098. C_B, C_C, C_NAE, C_O:
  5099. { For B/NAE:
  5100. Will never branch since an unsigned integer can never be below zero
  5101. For C/O:
  5102. Result cannot overflow because 0 is being subtracted
  5103. }
  5104. begin
  5105. if taicpu(hp1).opcode = A_Jcc then
  5106. begin
  5107. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  5108. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  5109. RemoveInstruction(hp1);
  5110. { Since hp1 was deleted, hp2 must not be updated }
  5111. Continue;
  5112. end
  5113. else
  5114. begin
  5115. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  5116. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  5117. taicpu(hp1).opcode := A_MOV;
  5118. taicpu(hp1).ops := 2;
  5119. taicpu(hp1).condition := C_None;
  5120. taicpu(hp1).opsize := S_B;
  5121. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5122. taicpu(hp1).loadconst(0, 0);
  5123. end;
  5124. end;
  5125. C_BE, C_NA:
  5126. begin
  5127. { Will only branch if equal to zero }
  5128. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  5129. taicpu(hp1).condition := C_E;
  5130. end;
  5131. C_A, C_NBE:
  5132. begin
  5133. { Will only branch if not equal to zero }
  5134. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  5135. taicpu(hp1).condition := C_NE;
  5136. end;
  5137. C_AE, C_NB, C_NC, C_NO:
  5138. begin
  5139. { Will always branch }
  5140. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  5141. if taicpu(hp1).opcode = A_Jcc then
  5142. begin
  5143. MakeUnconditional(taicpu(hp1));
  5144. { Any jumps/set that follow will now be dead code }
  5145. RemoveDeadCodeAfterJump(taicpu(hp1));
  5146. Break;
  5147. end
  5148. else
  5149. begin
  5150. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  5151. taicpu(hp1).opcode := A_MOV;
  5152. taicpu(hp1).ops := 2;
  5153. taicpu(hp1).condition := C_None;
  5154. taicpu(hp1).opsize := S_B;
  5155. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  5156. taicpu(hp1).loadconst(0, 1);
  5157. end;
  5158. end;
  5159. C_None:
  5160. InternalError(2020012201);
  5161. C_P, C_PE, C_NP, C_PO:
  5162. { We can't handle parity checks and they should never be generated
  5163. after a general-purpose CMP (it's used in some floating-point
  5164. comparisons that don't use CMP) }
  5165. InternalError(2020012202);
  5166. else
  5167. { Zero/Equality, Sign, their complements and all of the
  5168. signed comparisons do not need to be converted };
  5169. end;
  5170. hp2 := hp1;
  5171. end;
  5172. { Convert the instruction to a TEST }
  5173. taicpu(p).opcode := A_TEST;
  5174. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5175. Result := True;
  5176. Exit;
  5177. end
  5178. else if (taicpu(p).oper[0]^.val = 1) and
  5179. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5180. (taicpu(hp1).condition in [C_L, C_NGE]) then
  5181. begin
  5182. { Convert; To:
  5183. cmp $1,r/m cmp $0,r/m
  5184. jl @lbl jle @lbl
  5185. }
  5186. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  5187. taicpu(p).oper[0]^.val := 0;
  5188. taicpu(hp1).condition := C_LE;
  5189. { If the instruction is now "cmp $0,%reg", convert it to a
  5190. TEST (and effectively do the work of the "cmp $0,%reg" in
  5191. the block above)
  5192. If it's a reference, we can get away with not setting
  5193. Result to True because he haven't evaluated the jump
  5194. in this pass yet.
  5195. }
  5196. if (taicpu(p).oper[1]^.typ = top_reg) then
  5197. begin
  5198. taicpu(p).opcode := A_TEST;
  5199. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  5200. Result := True;
  5201. end;
  5202. Exit;
  5203. end
  5204. else if (taicpu(p).oper[1]^.typ = top_reg)
  5205. {$ifdef x86_64}
  5206. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  5207. {$endif x86_64}
  5208. then
  5209. begin
  5210. { cmp register,$8000 neg register
  5211. je target --> jo target
  5212. .... only if register is deallocated before jump.}
  5213. case Taicpu(p).opsize of
  5214. S_B: v:=$80;
  5215. S_W: v:=$8000;
  5216. S_L: v:=qword($80000000);
  5217. else
  5218. internalerror(2013112905);
  5219. end;
  5220. if (taicpu(p).oper[0]^.val=v) and
  5221. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  5222. (Taicpu(hp1).condition in [C_E,C_NE]) then
  5223. begin
  5224. TransferUsedRegs(TmpUsedRegs);
  5225. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  5226. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  5227. begin
  5228. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  5229. Taicpu(p).opcode:=A_NEG;
  5230. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  5231. Taicpu(p).clearop(1);
  5232. Taicpu(p).ops:=1;
  5233. if Taicpu(hp1).condition=C_E then
  5234. Taicpu(hp1).condition:=C_O
  5235. else
  5236. Taicpu(hp1).condition:=C_NO;
  5237. Result:=true;
  5238. exit;
  5239. end;
  5240. end;
  5241. end;
  5242. end;
  5243. if MatchInstruction(hp1,A_MOV,[]) and
  5244. (
  5245. (taicpu(p).oper[0]^.typ <> top_reg) or
  5246. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  5247. ) and
  5248. (
  5249. (taicpu(p).oper[1]^.typ <> top_reg) or
  5250. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  5251. ) and
  5252. (
  5253. { Make sure the register written to doesn't appear in the
  5254. cmp instruction (in a reference, say) }
  5255. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  5256. not RegInInstruction(taicpu(hp1).oper[1]^.reg, p)
  5257. ) then
  5258. begin
  5259. { If we have something like:
  5260. cmp ###,%reg1
  5261. mov 0,%reg2
  5262. And no registers are shared, move the MOV command to before the
  5263. comparison as this means it can be optimised without worrying
  5264. about the FLAGS register. (This combination is generated by
  5265. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  5266. }
  5267. SwapMovCmp(p, hp1);
  5268. Result := True;
  5269. Exit;
  5270. end;
  5271. end;
  5272. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  5273. var
  5274. hp1: tai;
  5275. begin
  5276. {
  5277. remove the second (v)pxor from
  5278. pxor reg,reg
  5279. ...
  5280. pxor reg,reg
  5281. }
  5282. Result:=false;
  5283. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5284. MatchOpType(taicpu(p),top_reg,top_reg) and
  5285. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5286. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5287. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5288. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  5289. begin
  5290. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  5291. RemoveInstruction(hp1);
  5292. Result:=true;
  5293. Exit;
  5294. end
  5295. {
  5296. replace
  5297. pxor reg1,reg1
  5298. movapd/s reg1,reg2
  5299. dealloc reg1
  5300. by
  5301. pxor reg2,reg2
  5302. }
  5303. else if GetNextInstruction(p,hp1) and
  5304. { we mix single and double opperations here because we assume that the compiler
  5305. generates vmovapd only after double operations and vmovaps only after single operations }
  5306. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5307. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  5308. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5309. (taicpu(p).oper[0]^.typ=top_reg) then
  5310. begin
  5311. TransferUsedRegs(TmpUsedRegs);
  5312. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5313. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5314. begin
  5315. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  5316. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5317. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  5318. RemoveInstruction(hp1);
  5319. result:=true;
  5320. end;
  5321. end;
  5322. end;
  5323. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  5324. var
  5325. hp1: tai;
  5326. begin
  5327. {
  5328. remove the second (v)pxor from
  5329. (v)pxor reg,reg
  5330. ...
  5331. (v)pxor reg,reg
  5332. }
  5333. Result:=false;
  5334. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  5335. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  5336. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  5337. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5338. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  5339. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  5340. begin
  5341. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  5342. RemoveInstruction(hp1);
  5343. Result:=true;
  5344. Exit;
  5345. end
  5346. else
  5347. Result:=OptPass1VOP(p);
  5348. end;
  5349. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  5350. var
  5351. hp1 : tai;
  5352. begin
  5353. result:=false;
  5354. { replace
  5355. IMul const,%mreg1,%mreg2
  5356. Mov %reg2,%mreg3
  5357. dealloc %mreg3
  5358. by
  5359. Imul const,%mreg1,%mreg23
  5360. }
  5361. if (taicpu(p).ops=3) and
  5362. GetNextInstruction(p,hp1) and
  5363. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5364. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5365. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5366. begin
  5367. TransferUsedRegs(TmpUsedRegs);
  5368. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5369. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5370. begin
  5371. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5372. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  5373. RemoveInstruction(hp1);
  5374. result:=true;
  5375. end;
  5376. end;
  5377. end;
  5378. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  5379. var
  5380. hp1 : tai;
  5381. begin
  5382. result:=false;
  5383. { replace
  5384. IMul %reg0,%reg1,%reg2
  5385. Mov %reg2,%reg3
  5386. dealloc %reg2
  5387. by
  5388. Imul %reg0,%reg1,%reg3
  5389. }
  5390. if GetNextInstruction(p,hp1) and
  5391. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5392. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5393. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5394. begin
  5395. TransferUsedRegs(TmpUsedRegs);
  5396. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5397. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5398. begin
  5399. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5400. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  5401. RemoveInstruction(hp1);
  5402. result:=true;
  5403. end;
  5404. end;
  5405. end;
  5406. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  5407. var
  5408. hp1: tai;
  5409. begin
  5410. Result:=false;
  5411. { get rid of
  5412. (v)cvtss2sd reg0,<reg1,>reg2
  5413. (v)cvtss2sd reg2,<reg2,>reg0
  5414. }
  5415. if GetNextInstruction(p,hp1) and
  5416. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  5417. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  5418. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  5419. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  5420. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  5421. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  5422. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5423. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  5424. )
  5425. ) then
  5426. begin
  5427. if getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg) then
  5428. begin
  5429. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  5430. RemoveCurrentP(p);
  5431. RemoveInstruction(hp1);
  5432. end
  5433. else
  5434. begin
  5435. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  5436. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  5437. taicpu(p).ops:=2;
  5438. taicpu(p).opcode:=A_VMOVAPS;
  5439. RemoveInstruction(hp1);
  5440. end;
  5441. Result:=true;
  5442. Exit;
  5443. end;
  5444. end;
  5445. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  5446. var
  5447. hp1, hp2, hp3, hp4, hp5: tai;
  5448. ThisReg: TRegister;
  5449. begin
  5450. Result := False;
  5451. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  5452. Exit;
  5453. {
  5454. convert
  5455. j<c> .L1
  5456. mov 1,reg
  5457. jmp .L2
  5458. .L1
  5459. mov 0,reg
  5460. .L2
  5461. into
  5462. mov 0,reg
  5463. set<not(c)> reg
  5464. take care of alignment and that the mov 0,reg is not converted into a xor as this
  5465. would destroy the flag contents
  5466. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  5467. executed at the same time as a previous comparison.
  5468. set<not(c)> reg
  5469. movzx reg, reg
  5470. }
  5471. if MatchInstruction(hp1,A_MOV,[]) and
  5472. (taicpu(hp1).oper[0]^.typ = top_const) and
  5473. (
  5474. (
  5475. (taicpu(hp1).oper[1]^.typ = top_reg)
  5476. {$ifdef i386}
  5477. { Under i386, ESI, EDI, EBP and ESP
  5478. don't have an 8-bit representation }
  5479. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5480. {$endif i386}
  5481. ) or (
  5482. {$ifdef i386}
  5483. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  5484. {$endif i386}
  5485. (taicpu(hp1).opsize = S_B)
  5486. )
  5487. ) and
  5488. GetNextInstruction(hp1,hp2) and
  5489. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  5490. GetNextInstruction(hp2,hp3) and
  5491. SkipAligns(hp3, hp3) and
  5492. (hp3.typ=ait_label) and
  5493. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  5494. GetNextInstruction(hp3,hp4) and
  5495. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  5496. (taicpu(hp4).oper[0]^.typ = top_const) and
  5497. (
  5498. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  5499. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  5500. ) and
  5501. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  5502. GetNextInstruction(hp4,hp5) and
  5503. SkipAligns(hp5, hp5) and
  5504. (hp5.typ=ait_label) and
  5505. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  5506. begin
  5507. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5508. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5509. tai_label(hp3).labsym.DecRefs;
  5510. { If this isn't the only reference to the middle label, we can
  5511. still make a saving - only that the first jump and everything
  5512. that follows will remain. }
  5513. if (tai_label(hp3).labsym.getrefs = 0) then
  5514. begin
  5515. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5516. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  5517. else
  5518. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  5519. { remove jump, first label and second MOV (also catching any aligns) }
  5520. repeat
  5521. if not GetNextInstruction(hp2, hp3) then
  5522. InternalError(2021040810);
  5523. RemoveInstruction(hp2);
  5524. hp2 := hp3;
  5525. until hp2 = hp5;
  5526. { Don't decrement reference count before the removal loop
  5527. above, otherwise GetNextInstruction won't stop on the
  5528. the label }
  5529. tai_label(hp5).labsym.DecRefs;
  5530. end
  5531. else
  5532. begin
  5533. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5534. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  5535. else
  5536. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  5537. end;
  5538. taicpu(p).opcode:=A_SETcc;
  5539. taicpu(p).opsize:=S_B;
  5540. taicpu(p).is_jmp:=False;
  5541. if taicpu(hp1).opsize=S_B then
  5542. begin
  5543. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  5544. if taicpu(hp1).oper[1]^.typ = top_reg then
  5545. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  5546. RemoveInstruction(hp1);
  5547. end
  5548. else
  5549. begin
  5550. { Will be a register because the size can't be S_B otherwise }
  5551. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  5552. taicpu(p).loadreg(0, ThisReg);
  5553. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  5554. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  5555. begin
  5556. case taicpu(hp1).opsize of
  5557. S_W:
  5558. taicpu(hp1).opsize := S_BW;
  5559. S_L:
  5560. taicpu(hp1).opsize := S_BL;
  5561. {$ifdef x86_64}
  5562. S_Q:
  5563. begin
  5564. taicpu(hp1).opsize := S_BL;
  5565. { Change the destination register to 32-bit }
  5566. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  5567. end;
  5568. {$endif x86_64}
  5569. else
  5570. InternalError(2021040820);
  5571. end;
  5572. taicpu(hp1).opcode := A_MOVZX;
  5573. taicpu(hp1).loadreg(0, ThisReg);
  5574. end
  5575. else
  5576. begin
  5577. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  5578. { hp1 is already a MOV instruction with the correct register }
  5579. taicpu(hp1).loadconst(0, 0);
  5580. { Inserting it right before p will guarantee that the flags are also tracked }
  5581. asml.Remove(hp1);
  5582. asml.InsertBefore(hp1, p);
  5583. end;
  5584. end;
  5585. Result:=true;
  5586. exit;
  5587. end
  5588. end;
  5589. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  5590. var
  5591. hp2, hp3, first_assignment: tai;
  5592. IncCount, OperIdx: Integer;
  5593. OrigLabel: TAsmLabel;
  5594. begin
  5595. Count := 0;
  5596. Result := False;
  5597. first_assignment := nil;
  5598. if (LoopCount >= 20) then
  5599. begin
  5600. { Guard against infinite loops }
  5601. Exit;
  5602. end;
  5603. if (taicpu(p).oper[0]^.typ <> top_ref) or
  5604. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  5605. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  5606. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  5607. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  5608. Exit;
  5609. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  5610. {
  5611. change
  5612. jmp .L1
  5613. ...
  5614. .L1:
  5615. mov ##, ## ( multiple movs possible )
  5616. jmp/ret
  5617. into
  5618. mov ##, ##
  5619. jmp/ret
  5620. }
  5621. if not Assigned(hp1) then
  5622. begin
  5623. hp1 := GetLabelWithSym(OrigLabel);
  5624. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  5625. Exit;
  5626. end;
  5627. hp2 := hp1;
  5628. while Assigned(hp2) do
  5629. begin
  5630. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  5631. SkipLabels(hp2,hp2);
  5632. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  5633. Break;
  5634. case taicpu(hp2).opcode of
  5635. A_MOVSS:
  5636. begin
  5637. if taicpu(hp2).ops = 0 then
  5638. { Wrong MOVSS }
  5639. Break;
  5640. Inc(Count);
  5641. if Count >= 5 then
  5642. { Too many to be worthwhile }
  5643. Break;
  5644. GetNextInstruction(hp2, hp2);
  5645. Continue;
  5646. end;
  5647. A_MOV,
  5648. A_MOVD,
  5649. A_MOVQ,
  5650. A_MOVSX,
  5651. {$ifdef x86_64}
  5652. A_MOVSXD,
  5653. {$endif x86_64}
  5654. A_MOVZX,
  5655. A_MOVAPS,
  5656. A_MOVUPS,
  5657. A_MOVSD,
  5658. A_MOVAPD,
  5659. A_MOVUPD,
  5660. A_MOVDQA,
  5661. A_MOVDQU,
  5662. A_VMOVSS,
  5663. A_VMOVAPS,
  5664. A_VMOVUPS,
  5665. A_VMOVSD,
  5666. A_VMOVAPD,
  5667. A_VMOVUPD,
  5668. A_VMOVDQA,
  5669. A_VMOVDQU:
  5670. begin
  5671. Inc(Count);
  5672. if Count >= 5 then
  5673. { Too many to be worthwhile }
  5674. Break;
  5675. GetNextInstruction(hp2, hp2);
  5676. Continue;
  5677. end;
  5678. A_JMP:
  5679. begin
  5680. { Guard against infinite loops }
  5681. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  5682. Exit;
  5683. { Analyse this jump first in case it also duplicates assignments }
  5684. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  5685. begin
  5686. { Something did change! }
  5687. Result := True;
  5688. Inc(Count, IncCount);
  5689. if Count >= 5 then
  5690. begin
  5691. { Too many to be worthwhile }
  5692. Exit;
  5693. end;
  5694. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  5695. Break;
  5696. end;
  5697. Result := True;
  5698. Break;
  5699. end;
  5700. A_RET:
  5701. begin
  5702. Result := True;
  5703. Break;
  5704. end;
  5705. else
  5706. Break;
  5707. end;
  5708. end;
  5709. if Result then
  5710. begin
  5711. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  5712. if Count = 0 then
  5713. begin
  5714. Result := False;
  5715. Exit;
  5716. end;
  5717. hp3 := p;
  5718. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  5719. while True do
  5720. begin
  5721. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  5722. SkipLabels(hp1,hp1);
  5723. if (hp1.typ <> ait_instruction) then
  5724. InternalError(2021040720);
  5725. case taicpu(hp1).opcode of
  5726. A_JMP:
  5727. begin
  5728. { Change the original jump to the new destination }
  5729. OrigLabel.decrefs;
  5730. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  5731. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  5732. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5733. if not Assigned(first_assignment) then
  5734. InternalError(2021040810)
  5735. else
  5736. p := first_assignment;
  5737. Exit;
  5738. end;
  5739. A_RET:
  5740. begin
  5741. { Now change the jump into a RET instruction }
  5742. ConvertJumpToRET(p, hp1);
  5743. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5744. if not Assigned(first_assignment) then
  5745. InternalError(2021040811)
  5746. else
  5747. p := first_assignment;
  5748. Exit;
  5749. end;
  5750. else
  5751. begin
  5752. { Duplicate the MOV instruction }
  5753. hp3:=tai(hp1.getcopy);
  5754. if first_assignment = nil then
  5755. first_assignment := hp3;
  5756. asml.InsertBefore(hp3, p);
  5757. { Make sure the compiler knows about any final registers written here }
  5758. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  5759. with taicpu(hp3).oper[OperIdx]^ do
  5760. begin
  5761. case typ of
  5762. top_ref:
  5763. begin
  5764. if (ref^.base <> NR_NO) and
  5765. (getsupreg(ref^.base) <> RS_ESP) and
  5766. (getsupreg(ref^.base) <> RS_EBP)
  5767. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  5768. then
  5769. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  5770. if (ref^.index <> NR_NO) and
  5771. (getsupreg(ref^.index) <> RS_ESP) and
  5772. (getsupreg(ref^.index) <> RS_EBP)
  5773. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  5774. (ref^.index <> ref^.base) then
  5775. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  5776. end;
  5777. top_reg:
  5778. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  5779. else
  5780. ;
  5781. end;
  5782. end;
  5783. end;
  5784. end;
  5785. if not GetNextInstruction(hp1, hp1) then
  5786. { Should have dropped out earlier }
  5787. InternalError(2021040710);
  5788. end;
  5789. end;
  5790. end;
  5791. procedure TX86AsmOptimizer.SwapMovCmp(var p, hp1: tai);
  5792. var
  5793. hp2: tai;
  5794. X: Integer;
  5795. begin
  5796. asml.Remove(hp1);
  5797. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  5798. if not GetLastInstruction(p, hp2) then
  5799. asml.InsertBefore(hp1, p)
  5800. else
  5801. asml.InsertAfter(hp1, hp2);
  5802. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and mov instructions to improve optimisation potential', hp1);
  5803. for X := 0 to 1 do
  5804. case taicpu(hp1).oper[X]^.typ of
  5805. top_reg:
  5806. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  5807. top_ref:
  5808. begin
  5809. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  5810. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  5811. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  5812. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  5813. end;
  5814. else
  5815. ;
  5816. end;
  5817. end;
  5818. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  5819. function IsXCHGAcceptable: Boolean; inline;
  5820. begin
  5821. { Always accept if optimising for size }
  5822. Result := (cs_opt_size in current_settings.optimizerswitches) or
  5823. (
  5824. {$ifdef x86_64}
  5825. { XCHG takes 3 cycles on AMD Athlon64 }
  5826. (current_settings.optimizecputype >= cpu_core_i)
  5827. {$else x86_64}
  5828. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  5829. than 3, so it becomes a saving compared to three MOVs with two of
  5830. them able to execute simultaneously. [Kit] }
  5831. (current_settings.optimizecputype >= cpu_PentiumM)
  5832. {$endif x86_64}
  5833. );
  5834. end;
  5835. var
  5836. NewRef: TReference;
  5837. hp1, hp2, hp3, hp4: Tai;
  5838. {$ifndef x86_64}
  5839. OperIdx: Integer;
  5840. {$endif x86_64}
  5841. NewInstr : Taicpu;
  5842. NewAligh : Tai_align;
  5843. DestLabel: TAsmLabel;
  5844. begin
  5845. Result:=false;
  5846. { This optimisation adds an instruction, so only do it for speed }
  5847. if not (cs_opt_size in current_settings.optimizerswitches) and
  5848. MatchOpType(taicpu(p), top_const, top_reg) and
  5849. (taicpu(p).oper[0]^.val = 0) then
  5850. begin
  5851. { To avoid compiler warning }
  5852. DestLabel := nil;
  5853. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  5854. InternalError(2021040750);
  5855. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  5856. Exit;
  5857. case hp1.typ of
  5858. ait_label:
  5859. begin
  5860. { Change:
  5861. mov $0,%reg mov $0,%reg
  5862. @Lbl1: @Lbl1:
  5863. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  5864. je @Lbl2 jne @Lbl2
  5865. To: To:
  5866. mov $0,%reg mov $0,%reg
  5867. jmp @Lbl2 jmp @Lbl3
  5868. (align) (align)
  5869. @Lbl1: @Lbl1:
  5870. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  5871. je @Lbl2 je @Lbl2
  5872. @Lbl3: <-- Only if label exists
  5873. (Not if it's optimised for size)
  5874. }
  5875. if not GetNextInstruction(hp1, hp2) then
  5876. Exit;
  5877. if not (cs_opt_size in current_settings.optimizerswitches) and
  5878. (hp2.typ = ait_instruction) and
  5879. (
  5880. { Register sizes must exactly match }
  5881. (
  5882. (taicpu(hp2).opcode = A_CMP) and
  5883. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  5884. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5885. ) or (
  5886. (taicpu(hp2).opcode = A_TEST) and
  5887. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5888. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5889. )
  5890. ) and GetNextInstruction(hp2, hp3) and
  5891. (hp3.typ = ait_instruction) and
  5892. (taicpu(hp3).opcode = A_JCC) and
  5893. (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
  5894. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  5895. begin
  5896. { Check condition of jump }
  5897. { Always true? }
  5898. if condition_in(C_E, taicpu(hp3).condition) then
  5899. begin
  5900. { Copy label symbol and obtain matching label entry for the
  5901. conditional jump, as this will be our destination}
  5902. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  5903. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  5904. Result := True;
  5905. end
  5906. { Always false? }
  5907. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  5908. begin
  5909. { This is only worth it if there's a jump to take }
  5910. case hp2.typ of
  5911. ait_instruction:
  5912. begin
  5913. if taicpu(hp2).opcode = A_JMP then
  5914. begin
  5915. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5916. { An unconditional jump follows the conditional jump which will always be false,
  5917. so use this jump's destination for the new jump }
  5918. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  5919. Result := True;
  5920. end
  5921. else if taicpu(hp2).opcode = A_JCC then
  5922. begin
  5923. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5924. if condition_in(C_E, taicpu(hp2).condition) then
  5925. begin
  5926. { A second conditional jump follows the conditional jump which will always be false,
  5927. while the second jump is always True, so use this jump's destination for the new jump }
  5928. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  5929. Result := True;
  5930. end;
  5931. { Don't risk it if the jump isn't always true (Result remains False) }
  5932. end;
  5933. end;
  5934. else
  5935. { If anything else don't optimise };
  5936. end;
  5937. end;
  5938. if Result then
  5939. begin
  5940. { Just so we have something to insert as a paremeter}
  5941. reference_reset(NewRef, 1, []);
  5942. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  5943. { Now actually load the correct parameter }
  5944. NewInstr.loadsymbol(0, DestLabel, 0);
  5945. { Get instruction before original label (may not be p under -O3) }
  5946. if not GetLastInstruction(hp1, hp2) then
  5947. { Shouldn't fail here }
  5948. InternalError(2021040701);
  5949. DestLabel.increfs;
  5950. AsmL.InsertAfter(NewInstr, hp2);
  5951. { Add new alignment field }
  5952. (* AsmL.InsertAfter(
  5953. cai_align.create_max(
  5954. current_settings.alignment.jumpalign,
  5955. current_settings.alignment.jumpalignskipmax
  5956. ),
  5957. NewInstr
  5958. ); *)
  5959. end;
  5960. Exit;
  5961. end;
  5962. end;
  5963. else
  5964. ;
  5965. end;
  5966. end;
  5967. if not GetNextInstruction(p, hp1) then
  5968. Exit;
  5969. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  5970. begin
  5971. { Sometimes the MOVs that OptPass2JMP produces can be improved
  5972. further, but we can't just put this jump optimisation in pass 1
  5973. because it tends to perform worse when conditional jumps are
  5974. nearby (e.g. when converting CMOV instructions). [Kit] }
  5975. if OptPass2JMP(hp1) then
  5976. { call OptPass1MOV once to potentially merge any MOVs that were created }
  5977. Result := OptPass1MOV(p)
  5978. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  5979. returned True and the instruction is still a MOV, thus checking
  5980. the optimisations below }
  5981. { If OptPass2JMP returned False, no optimisations were done to
  5982. the jump and there are no further optimisations that can be done
  5983. to the MOV instruction on this pass }
  5984. end
  5985. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5986. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  5987. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5988. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5989. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5990. { be lazy, checking separately for sub would be slightly better }
  5991. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  5992. begin
  5993. { Change:
  5994. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  5995. addl/q $x,%reg2 subl/q $x,%reg2
  5996. To:
  5997. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  5998. }
  5999. TransferUsedRegs(TmpUsedRegs);
  6000. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6001. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6002. if not GetNextInstruction(hp1, hp2) or
  6003. (
  6004. { The FLAGS register isn't always tracked properly, so do not
  6005. perform this optimisation if a conditional statement follows }
  6006. not RegReadByInstruction(NR_DEFAULTFLAGS, hp2) and
  6007. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)
  6008. ) then
  6009. begin
  6010. reference_reset(NewRef, 1, []);
  6011. NewRef.base := taicpu(p).oper[0]^.reg;
  6012. NewRef.scalefactor := 1;
  6013. if taicpu(hp1).opcode = A_ADD then
  6014. begin
  6015. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  6016. NewRef.offset := taicpu(hp1).oper[0]^.val;
  6017. end
  6018. else
  6019. begin
  6020. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  6021. NewRef.offset := -taicpu(hp1).oper[0]^.val;
  6022. end;
  6023. taicpu(p).opcode := A_LEA;
  6024. taicpu(p).loadref(0, NewRef);
  6025. RemoveInstruction(hp1);
  6026. Result := True;
  6027. Exit;
  6028. end;
  6029. end
  6030. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6031. {$ifdef x86_64}
  6032. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  6033. {$else x86_64}
  6034. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  6035. {$endif x86_64}
  6036. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6037. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  6038. { mov reg1, reg2 mov reg1, reg2
  6039. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  6040. begin
  6041. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6042. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  6043. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  6044. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  6045. TransferUsedRegs(TmpUsedRegs);
  6046. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6047. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  6048. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  6049. then
  6050. begin
  6051. RemoveCurrentP(p, hp1);
  6052. Result:=true;
  6053. end;
  6054. exit;
  6055. end
  6056. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6057. IsXCHGAcceptable and
  6058. { XCHG doesn't support 8-byte registers }
  6059. (taicpu(p).opsize <> S_B) and
  6060. MatchInstruction(hp1, A_MOV, []) and
  6061. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6062. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  6063. GetNextInstruction(hp1, hp2) and
  6064. MatchInstruction(hp2, A_MOV, []) and
  6065. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  6066. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  6067. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  6068. begin
  6069. { mov %reg1,%reg2
  6070. mov %reg3,%reg1 -> xchg %reg3,%reg1
  6071. mov %reg2,%reg3
  6072. (%reg2 not used afterwards)
  6073. Note that xchg takes 3 cycles to execute, and generally mov's take
  6074. only one cycle apiece, but the first two mov's can be executed in
  6075. parallel, only taking 2 cycles overall. Older processors should
  6076. therefore only optimise for size. [Kit]
  6077. }
  6078. TransferUsedRegs(TmpUsedRegs);
  6079. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6080. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6081. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  6082. begin
  6083. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  6084. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  6085. taicpu(hp1).opcode := A_XCHG;
  6086. RemoveCurrentP(p, hp1);
  6087. RemoveInstruction(hp2);
  6088. Result := True;
  6089. Exit;
  6090. end;
  6091. end
  6092. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  6093. MatchInstruction(hp1, A_SAR, []) then
  6094. begin
  6095. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  6096. begin
  6097. { the use of %edx also covers the opsize being S_L }
  6098. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  6099. begin
  6100. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  6101. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  6102. (taicpu(p).oper[1]^.reg = NR_EDX) then
  6103. begin
  6104. { Change:
  6105. movl %eax,%edx
  6106. sarl $31,%edx
  6107. To:
  6108. cltd
  6109. }
  6110. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  6111. RemoveInstruction(hp1);
  6112. taicpu(p).opcode := A_CDQ;
  6113. taicpu(p).opsize := S_NO;
  6114. taicpu(p).clearop(1);
  6115. taicpu(p).clearop(0);
  6116. taicpu(p).ops:=0;
  6117. Result := True;
  6118. end
  6119. else if (cs_opt_size in current_settings.optimizerswitches) and
  6120. (taicpu(p).oper[0]^.reg = NR_EDX) and
  6121. (taicpu(p).oper[1]^.reg = NR_EAX) then
  6122. begin
  6123. { Change:
  6124. movl %edx,%eax
  6125. sarl $31,%edx
  6126. To:
  6127. movl %edx,%eax
  6128. cltd
  6129. Note that this creates a dependency between the two instructions,
  6130. so only perform if optimising for size.
  6131. }
  6132. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  6133. taicpu(hp1).opcode := A_CDQ;
  6134. taicpu(hp1).opsize := S_NO;
  6135. taicpu(hp1).clearop(1);
  6136. taicpu(hp1).clearop(0);
  6137. taicpu(hp1).ops:=0;
  6138. end;
  6139. {$ifndef x86_64}
  6140. end
  6141. { Don't bother if CMOV is supported, because a more optimal
  6142. sequence would have been generated for the Abs() intrinsic }
  6143. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  6144. { the use of %eax also covers the opsize being S_L }
  6145. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  6146. (taicpu(p).oper[0]^.reg = NR_EAX) and
  6147. (taicpu(p).oper[1]^.reg = NR_EDX) and
  6148. GetNextInstruction(hp1, hp2) and
  6149. MatchInstruction(hp2, A_XOR, [S_L]) and
  6150. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  6151. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  6152. GetNextInstruction(hp2, hp3) and
  6153. MatchInstruction(hp3, A_SUB, [S_L]) and
  6154. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  6155. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  6156. begin
  6157. { Change:
  6158. movl %eax,%edx
  6159. sarl $31,%eax
  6160. xorl %eax,%edx
  6161. subl %eax,%edx
  6162. (Instruction that uses %edx)
  6163. (%eax deallocated)
  6164. (%edx deallocated)
  6165. To:
  6166. cltd
  6167. xorl %edx,%eax <-- Note the registers have swapped
  6168. subl %edx,%eax
  6169. (Instruction that uses %eax) <-- %eax rather than %edx
  6170. }
  6171. TransferUsedRegs(TmpUsedRegs);
  6172. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6173. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6174. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6175. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  6176. begin
  6177. if GetNextInstruction(hp3, hp4) and
  6178. not RegModifiedByInstruction(NR_EDX, hp4) and
  6179. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  6180. begin
  6181. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  6182. taicpu(p).opcode := A_CDQ;
  6183. taicpu(p).clearop(1);
  6184. taicpu(p).clearop(0);
  6185. taicpu(p).ops:=0;
  6186. RemoveInstruction(hp1);
  6187. taicpu(hp2).loadreg(0, NR_EDX);
  6188. taicpu(hp2).loadreg(1, NR_EAX);
  6189. taicpu(hp3).loadreg(0, NR_EDX);
  6190. taicpu(hp3).loadreg(1, NR_EAX);
  6191. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  6192. { Convert references in the following instruction (hp4) from %edx to %eax }
  6193. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  6194. with taicpu(hp4).oper[OperIdx]^ do
  6195. case typ of
  6196. top_reg:
  6197. if getsupreg(reg) = RS_EDX then
  6198. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6199. top_ref:
  6200. begin
  6201. if getsupreg(reg) = RS_EDX then
  6202. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6203. if getsupreg(reg) = RS_EDX then
  6204. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  6205. end;
  6206. else
  6207. ;
  6208. end;
  6209. end;
  6210. end;
  6211. {$else x86_64}
  6212. end;
  6213. end
  6214. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  6215. { the use of %rdx also covers the opsize being S_Q }
  6216. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  6217. begin
  6218. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  6219. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  6220. (taicpu(p).oper[1]^.reg = NR_RDX) then
  6221. begin
  6222. { Change:
  6223. movq %rax,%rdx
  6224. sarq $63,%rdx
  6225. To:
  6226. cqto
  6227. }
  6228. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  6229. RemoveInstruction(hp1);
  6230. taicpu(p).opcode := A_CQO;
  6231. taicpu(p).opsize := S_NO;
  6232. taicpu(p).clearop(1);
  6233. taicpu(p).clearop(0);
  6234. taicpu(p).ops:=0;
  6235. Result := True;
  6236. end
  6237. else if (cs_opt_size in current_settings.optimizerswitches) and
  6238. (taicpu(p).oper[0]^.reg = NR_RDX) and
  6239. (taicpu(p).oper[1]^.reg = NR_RAX) then
  6240. begin
  6241. { Change:
  6242. movq %rdx,%rax
  6243. sarq $63,%rdx
  6244. To:
  6245. movq %rdx,%rax
  6246. cqto
  6247. Note that this creates a dependency between the two instructions,
  6248. so only perform if optimising for size.
  6249. }
  6250. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  6251. taicpu(hp1).opcode := A_CQO;
  6252. taicpu(hp1).opsize := S_NO;
  6253. taicpu(hp1).clearop(1);
  6254. taicpu(hp1).clearop(0);
  6255. taicpu(hp1).ops:=0;
  6256. {$endif x86_64}
  6257. end;
  6258. end;
  6259. end
  6260. else if MatchInstruction(hp1, A_MOV, []) and
  6261. (taicpu(hp1).oper[1]^.typ = top_reg) then
  6262. { Though "GetNextInstruction" could be factored out, along with
  6263. the instructions that depend on hp2, it is an expensive call that
  6264. should be delayed for as long as possible, hence we do cheaper
  6265. checks first that are likely to be False. [Kit] }
  6266. begin
  6267. if (
  6268. (
  6269. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  6270. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  6271. (
  6272. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6273. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  6274. )
  6275. ) or
  6276. (
  6277. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  6278. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  6279. (
  6280. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6281. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  6282. )
  6283. )
  6284. ) and
  6285. GetNextInstruction(hp1, hp2) and
  6286. MatchInstruction(hp2, A_SAR, []) and
  6287. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  6288. begin
  6289. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  6290. begin
  6291. { Change:
  6292. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  6293. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  6294. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  6295. To:
  6296. movl r/m,%eax <- Note the change in register
  6297. cltd
  6298. }
  6299. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  6300. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  6301. taicpu(p).loadreg(1, NR_EAX);
  6302. taicpu(hp1).opcode := A_CDQ;
  6303. taicpu(hp1).clearop(1);
  6304. taicpu(hp1).clearop(0);
  6305. taicpu(hp1).ops:=0;
  6306. RemoveInstruction(hp2);
  6307. (*
  6308. {$ifdef x86_64}
  6309. end
  6310. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  6311. { This code sequence does not get generated - however it might become useful
  6312. if and when 128-bit signed integer types make an appearance, so the code
  6313. is kept here for when it is eventually needed. [Kit] }
  6314. (
  6315. (
  6316. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  6317. (
  6318. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6319. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  6320. )
  6321. ) or
  6322. (
  6323. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  6324. (
  6325. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  6326. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  6327. )
  6328. )
  6329. ) and
  6330. GetNextInstruction(hp1, hp2) and
  6331. MatchInstruction(hp2, A_SAR, [S_Q]) and
  6332. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  6333. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  6334. begin
  6335. { Change:
  6336. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  6337. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  6338. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  6339. To:
  6340. movq r/m,%rax <- Note the change in register
  6341. cqto
  6342. }
  6343. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  6344. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  6345. taicpu(p).loadreg(1, NR_RAX);
  6346. taicpu(hp1).opcode := A_CQO;
  6347. taicpu(hp1).clearop(1);
  6348. taicpu(hp1).clearop(0);
  6349. taicpu(hp1).ops:=0;
  6350. RemoveInstruction(hp2);
  6351. {$endif x86_64}
  6352. *)
  6353. end;
  6354. end;
  6355. {$ifdef x86_64}
  6356. end
  6357. else if (taicpu(p).opsize = S_L) and
  6358. (taicpu(p).oper[1]^.typ = top_reg) and
  6359. (
  6360. MatchInstruction(hp1, A_MOV,[]) and
  6361. (taicpu(hp1).opsize = S_L) and
  6362. (taicpu(hp1).oper[1]^.typ = top_reg)
  6363. ) and (
  6364. GetNextInstruction(hp1, hp2) and
  6365. (tai(hp2).typ=ait_instruction) and
  6366. (taicpu(hp2).opsize = S_Q) and
  6367. (
  6368. (
  6369. MatchInstruction(hp2, A_ADD,[]) and
  6370. (taicpu(hp2).opsize = S_Q) and
  6371. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  6372. (
  6373. (
  6374. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  6375. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6376. ) or (
  6377. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6378. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  6379. )
  6380. )
  6381. ) or (
  6382. MatchInstruction(hp2, A_LEA,[]) and
  6383. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  6384. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  6385. (
  6386. (
  6387. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  6388. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6389. ) or (
  6390. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6391. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  6392. )
  6393. ) and (
  6394. (
  6395. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  6396. ) or (
  6397. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  6398. )
  6399. )
  6400. )
  6401. )
  6402. ) and (
  6403. GetNextInstruction(hp2, hp3) and
  6404. MatchInstruction(hp3, A_SHR,[]) and
  6405. (taicpu(hp3).opsize = S_Q) and
  6406. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  6407. (taicpu(hp3).oper[0]^.val = 1) and
  6408. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  6409. ) then
  6410. begin
  6411. { Change movl x, reg1d movl x, reg1d
  6412. movl y, reg2d movl y, reg2d
  6413. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  6414. shrq $1, reg1q shrq $1, reg1q
  6415. ( reg1d and reg2d can be switched around in the first two instructions )
  6416. To movl x, reg1d
  6417. addl y, reg1d
  6418. rcrl $1, reg1d
  6419. This corresponds to the common expression (x + y) shr 1, where
  6420. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  6421. smaller code, but won't account for x + y causing an overflow). [Kit]
  6422. }
  6423. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  6424. { Change first MOV command to have the same register as the final output }
  6425. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  6426. else
  6427. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  6428. { Change second MOV command to an ADD command. This is easier than
  6429. converting the existing command because it means we don't have to
  6430. touch 'y', which might be a complicated reference, and also the
  6431. fact that the third command might either be ADD or LEA. [Kit] }
  6432. taicpu(hp1).opcode := A_ADD;
  6433. { Delete old ADD/LEA instruction }
  6434. RemoveInstruction(hp2);
  6435. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  6436. taicpu(hp3).opcode := A_RCR;
  6437. taicpu(hp3).changeopsize(S_L);
  6438. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  6439. {$endif x86_64}
  6440. end;
  6441. end;
  6442. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  6443. var
  6444. ThisReg: TRegister;
  6445. MinSize, MaxSize, TrySmaller, TargetSize: TOpSize;
  6446. TargetSubReg: TSubRegister;
  6447. hp1, hp2: tai;
  6448. RegInUse, RegChanged, p_removed: Boolean;
  6449. { Store list of found instructions so we don't have to call
  6450. GetNextInstructionUsingReg multiple times }
  6451. InstrList: array of taicpu;
  6452. InstrMax, Index: Integer;
  6453. UpperLimit, TrySmallerLimit: TCgInt;
  6454. PreMessage: string;
  6455. { Data flow analysis }
  6456. TestValMin, TestValMax: TCgInt;
  6457. SmallerOverflow: Boolean;
  6458. begin
  6459. Result := False;
  6460. p_removed := False;
  6461. { This is anything but quick! }
  6462. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  6463. Exit;
  6464. SetLength(InstrList, 0);
  6465. InstrMax := -1;
  6466. ThisReg := taicpu(p).oper[1]^.reg;
  6467. case taicpu(p).opsize of
  6468. S_BW, S_BL:
  6469. begin
  6470. {$if defined(i386) or defined(i8086)}
  6471. { If the target size is 8-bit, make sure we can actually encode it }
  6472. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  6473. Exit;
  6474. {$endif i386 or i8086}
  6475. UpperLimit := $FF;
  6476. MinSize := S_B;
  6477. if taicpu(p).opsize = S_BW then
  6478. MaxSize := S_W
  6479. else
  6480. MaxSize := S_L;
  6481. end;
  6482. S_WL:
  6483. begin
  6484. UpperLimit := $FFFF;
  6485. MinSize := S_W;
  6486. MaxSize := S_L;
  6487. end
  6488. else
  6489. InternalError(2020112301);
  6490. end;
  6491. TestValMin := 0;
  6492. TestValMax := UpperLimit;
  6493. TrySmallerLimit := UpperLimit;
  6494. TrySmaller := S_NO;
  6495. SmallerOverflow := False;
  6496. RegChanged := False;
  6497. hp1 := p;
  6498. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  6499. (hp1.typ = ait_instruction) and
  6500. (
  6501. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  6502. instruction that doesn't actually contain ThisReg }
  6503. (cs_opt_level3 in current_settings.optimizerswitches) or
  6504. RegInInstruction(ThisReg, hp1)
  6505. ) do
  6506. begin
  6507. case taicpu(hp1).opcode of
  6508. A_INC,A_DEC:
  6509. begin
  6510. { Has to be an exact match on the register }
  6511. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  6512. Break;
  6513. if taicpu(hp1).opcode = A_INC then
  6514. begin
  6515. Inc(TestValMin);
  6516. Inc(TestValMax);
  6517. end
  6518. else
  6519. begin
  6520. Dec(TestValMin);
  6521. Dec(TestValMax);
  6522. end;
  6523. end;
  6524. A_CMP:
  6525. begin
  6526. if (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6527. { Has to be an exact match on the register }
  6528. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6529. (taicpu(hp1).oper[0]^.typ <> top_const) or
  6530. { Make sure the comparison value is not smaller than the
  6531. smallest allowed signed value for the minimum size (e.g.
  6532. -128 for 8-bit) }
  6533. not (
  6534. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6535. { Is it in the negative range? }
  6536. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6537. ) then
  6538. Break;
  6539. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6540. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6541. if (TestValMin < TrySmallerLimit) or (TestValMax < TrySmallerLimit) or
  6542. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6543. { Overflow }
  6544. Break;
  6545. { Check to see if the active register is used afterwards }
  6546. TransferUsedRegs(TmpUsedRegs);
  6547. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  6548. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6549. begin
  6550. case MinSize of
  6551. S_B:
  6552. TargetSubReg := R_SUBL;
  6553. S_W:
  6554. TargetSubReg := R_SUBW;
  6555. else
  6556. InternalError(2021051002);
  6557. end;
  6558. { Update the register to its new size }
  6559. setsubreg(ThisReg, TargetSubReg);
  6560. taicpu(hp1).oper[1]^.reg := ThisReg;
  6561. taicpu(hp1).opsize := MinSize;
  6562. { Convert the input MOVZX to a MOV }
  6563. if (taicpu(p).oper[0]^.typ = top_reg) and
  6564. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6565. begin
  6566. { Or remove it completely! }
  6567. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  6568. RemoveCurrentP(p);
  6569. p_removed := True;
  6570. end
  6571. else
  6572. begin
  6573. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  6574. taicpu(p).opcode := A_MOV;
  6575. taicpu(p).oper[1]^.reg := ThisReg;
  6576. taicpu(p).opsize := MinSize;
  6577. end;
  6578. if (InstrMax >= 0) then
  6579. begin
  6580. for Index := 0 to InstrMax do
  6581. begin
  6582. { If p_removed is true, then the original MOV/Z was removed
  6583. and removing the AND instruction may not be safe if it
  6584. appears first }
  6585. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6586. InternalError(2020112311);
  6587. if InstrList[Index].oper[0]^.typ = top_reg then
  6588. InstrList[Index].oper[0]^.reg := ThisReg;
  6589. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6590. InstrList[Index].opsize := MinSize;
  6591. end;
  6592. end;
  6593. Result := True;
  6594. Exit;
  6595. end;
  6596. end;
  6597. { OR and XOR are not included because they can too easily fool
  6598. the data flow analysis (they can cause non-linear behaviour) }
  6599. A_ADD,A_SUB,A_AND,A_SHL,A_SHR:
  6600. begin
  6601. if
  6602. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6603. { Has to be an exact match on the register }
  6604. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  6605. (
  6606. (
  6607. (taicpu(hp1).oper[0]^.typ = top_const) and
  6608. (
  6609. (
  6610. (taicpu(hp1).opcode = A_SHL) and
  6611. (
  6612. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  6613. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  6614. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  6615. )
  6616. ) or (
  6617. (taicpu(hp1).opcode <> A_SHL) and
  6618. (
  6619. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6620. { Is it in the negative range? }
  6621. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6622. )
  6623. )
  6624. )
  6625. ) or (
  6626. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  6627. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  6628. )
  6629. ) then
  6630. Break;
  6631. case taicpu(hp1).opcode of
  6632. A_ADD:
  6633. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6634. begin
  6635. TestValMin := TestValMin * 2;
  6636. TestValMax := TestValMax * 2;
  6637. end
  6638. else
  6639. begin
  6640. TestValMin := TestValMin + taicpu(hp1).oper[0]^.val;
  6641. TestValMax := TestValMax + taicpu(hp1).oper[0]^.val;
  6642. end;
  6643. A_SUB:
  6644. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6645. begin
  6646. TestValMin := 0;
  6647. TestValMax := 0;
  6648. end
  6649. else
  6650. begin
  6651. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6652. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6653. end;
  6654. A_AND:
  6655. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6656. begin
  6657. { we might be able to go smaller if AND appears first }
  6658. if InstrMax = -1 then
  6659. case MinSize of
  6660. S_B:
  6661. ;
  6662. S_W:
  6663. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6664. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6665. begin
  6666. TrySmaller := S_B;
  6667. TrySmallerLimit := $FF;
  6668. end;
  6669. S_L:
  6670. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6671. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6672. begin
  6673. TrySmaller := S_B;
  6674. TrySmallerLimit := $FF;
  6675. end
  6676. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  6677. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  6678. begin
  6679. TrySmaller := S_W;
  6680. TrySmallerLimit := $FFFF;
  6681. end;
  6682. else
  6683. InternalError(2020112320);
  6684. end;
  6685. TestValMin := TestValMin and taicpu(hp1).oper[0]^.val;
  6686. TestValMax := TestValMax and taicpu(hp1).oper[0]^.val;
  6687. end;
  6688. A_SHL:
  6689. begin
  6690. TestValMin := TestValMin shl taicpu(hp1).oper[0]^.val;
  6691. TestValMax := TestValMax shl taicpu(hp1).oper[0]^.val;
  6692. end;
  6693. A_SHR:
  6694. begin
  6695. { we might be able to go smaller if SHR appears first }
  6696. if InstrMax = -1 then
  6697. case MinSize of
  6698. S_B:
  6699. ;
  6700. S_W:
  6701. if (taicpu(hp1).oper[0]^.val >= 8) then
  6702. begin
  6703. TrySmaller := S_B;
  6704. TrySmallerLimit := $FF;
  6705. end;
  6706. S_L:
  6707. if (taicpu(hp1).oper[0]^.val >= 24) then
  6708. begin
  6709. TrySmaller := S_B;
  6710. TrySmallerLimit := $FF;
  6711. end
  6712. else if (taicpu(hp1).oper[0]^.val >= 16) then
  6713. begin
  6714. TrySmaller := S_W;
  6715. TrySmallerLimit := $FFFF;
  6716. end;
  6717. else
  6718. InternalError(2020112321);
  6719. end;
  6720. TestValMin := TestValMin shr taicpu(hp1).oper[0]^.val;
  6721. TestValMax := TestValMax shr taicpu(hp1).oper[0]^.val;
  6722. end;
  6723. else
  6724. InternalError(2020112303);
  6725. end;
  6726. end;
  6727. (*
  6728. A_IMUL:
  6729. case taicpu(hp1).ops of
  6730. 2:
  6731. begin
  6732. if not MatchOpType(hp1, top_reg, top_reg) or
  6733. { Has to be an exact match on the register }
  6734. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  6735. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  6736. Break;
  6737. TestValMin := TestValMin * TestValMin;
  6738. TestValMax := TestValMax * TestValMax;
  6739. end;
  6740. 3:
  6741. begin
  6742. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6743. { Has to be an exact match on the register }
  6744. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6745. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6746. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6747. { Is it in the negative range? }
  6748. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6749. Break;
  6750. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  6751. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  6752. end;
  6753. else
  6754. Break;
  6755. end;
  6756. A_IDIV:
  6757. case taicpu(hp1).ops of
  6758. 3:
  6759. begin
  6760. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6761. { Has to be an exact match on the register }
  6762. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6763. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6764. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6765. { Is it in the negative range? }
  6766. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6767. Break;
  6768. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  6769. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  6770. end;
  6771. else
  6772. Break;
  6773. end;
  6774. *)
  6775. A_MOVZX:
  6776. begin
  6777. if not MatchOpType(taicpu(hp1), top_reg, top_reg) then
  6778. Break;
  6779. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  6780. begin
  6781. { Because hp1 was obtained via GetNextInstructionUsingReg
  6782. and ThisReg doesn't appear in the first operand, it
  6783. must appear in the second operand and hence gets
  6784. overwritten }
  6785. if (InstrMax = -1) and
  6786. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6787. begin
  6788. { The two MOVZX instructions are adjacent, so remove the first one }
  6789. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  6790. RemoveCurrentP(p);
  6791. Result := True;
  6792. Exit;
  6793. end;
  6794. Break;
  6795. end;
  6796. { The objective here is to try to find a combination that
  6797. removes one of the MOV/Z instructions. }
  6798. case taicpu(hp1).opsize of
  6799. S_WL:
  6800. if (MinSize in [S_B, S_W]) then
  6801. begin
  6802. TargetSize := S_L;
  6803. TargetSubReg := R_SUBD;
  6804. end
  6805. else if ((TrySmaller in [S_B, S_W]) and not SmallerOverflow) then
  6806. begin
  6807. TargetSize := TrySmaller;
  6808. if TrySmaller = S_B then
  6809. TargetSubReg := R_SUBL
  6810. else
  6811. TargetSubReg := R_SUBW;
  6812. end
  6813. else
  6814. Break;
  6815. S_BW:
  6816. if (MinSize in [S_B, S_W]) then
  6817. begin
  6818. TargetSize := S_W;
  6819. TargetSubReg := R_SUBW;
  6820. end
  6821. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6822. begin
  6823. TargetSize := S_B;
  6824. TargetSubReg := R_SUBL;
  6825. end
  6826. else
  6827. Break;
  6828. S_BL:
  6829. if (MinSize in [S_B, S_W]) then
  6830. begin
  6831. TargetSize := S_L;
  6832. TargetSubReg := R_SUBD;
  6833. end
  6834. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6835. begin
  6836. TargetSize := S_B;
  6837. TargetSubReg := R_SUBL;
  6838. end
  6839. else
  6840. Break;
  6841. else
  6842. InternalError(2020112302);
  6843. end;
  6844. { Update the register to its new size }
  6845. setsubreg(ThisReg, TargetSubReg);
  6846. if TargetSize = MinSize then
  6847. begin
  6848. { Convert the input MOVZX to a MOV }
  6849. if (taicpu(p).oper[0]^.typ = top_reg) and
  6850. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6851. begin
  6852. { Or remove it completely! }
  6853. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  6854. RemoveCurrentP(p);
  6855. p_removed := True;
  6856. end
  6857. else
  6858. begin
  6859. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  6860. taicpu(p).opcode := A_MOV;
  6861. taicpu(p).oper[1]^.reg := ThisReg;
  6862. taicpu(p).opsize := TargetSize;
  6863. end;
  6864. Result := True;
  6865. end
  6866. else if TargetSize <> MaxSize then
  6867. begin
  6868. case MaxSize of
  6869. S_L:
  6870. if TargetSize = S_W then
  6871. begin
  6872. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  6873. taicpu(p).opsize := S_BW;
  6874. taicpu(p).oper[1]^.reg := ThisReg;
  6875. Result := True;
  6876. end
  6877. else
  6878. InternalError(2020112341);
  6879. S_W:
  6880. if TargetSize = S_L then
  6881. begin
  6882. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  6883. taicpu(p).opsize := S_BL;
  6884. taicpu(p).oper[1]^.reg := ThisReg;
  6885. Result := True;
  6886. end
  6887. else
  6888. InternalError(2020112342);
  6889. else
  6890. ;
  6891. end;
  6892. end;
  6893. if (MaxSize = TargetSize) or
  6894. ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  6895. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  6896. begin
  6897. { Convert the output MOVZX to a MOV }
  6898. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6899. begin
  6900. { Or remove it completely! }
  6901. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  6902. { Be careful; if p = hp1 and p was also removed, p
  6903. will become a dangling pointer }
  6904. if p = hp1 then
  6905. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6906. else
  6907. RemoveInstruction(hp1);
  6908. end
  6909. else
  6910. begin
  6911. taicpu(hp1).opcode := A_MOV;
  6912. taicpu(hp1).oper[0]^.reg := ThisReg;
  6913. taicpu(hp1).opsize := TargetSize;
  6914. { Check to see if the active register is used afterwards;
  6915. if not, we can change it and make a saving. }
  6916. RegInUse := False;
  6917. TransferUsedRegs(TmpUsedRegs);
  6918. { The target register may be marked as in use to cross
  6919. a jump to a distant label, so exclude it }
  6920. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  6921. hp2 := p;
  6922. repeat
  6923. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6924. { Explicitly check for the excluded register (don't include the first
  6925. instruction as it may be reading from here }
  6926. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  6927. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  6928. begin
  6929. RegInUse := True;
  6930. Break;
  6931. end;
  6932. if not GetNextInstruction(hp2, hp2) then
  6933. InternalError(2020112340);
  6934. until (hp2 = hp1);
  6935. if not RegInUse and not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6936. begin
  6937. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  6938. ThisReg := taicpu(hp1).oper[1]^.reg;
  6939. RegChanged := True;
  6940. TransferUsedRegs(TmpUsedRegs);
  6941. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  6942. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  6943. if p = hp1 then
  6944. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6945. else
  6946. RemoveInstruction(hp1);
  6947. { Instruction will become "mov %reg,%reg" }
  6948. if not p_removed and (taicpu(p).opcode = A_MOV) and
  6949. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  6950. begin
  6951. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  6952. RemoveCurrentP(p);
  6953. p_removed := True;
  6954. end
  6955. else
  6956. taicpu(p).oper[1]^.reg := ThisReg;
  6957. Result := True;
  6958. end
  6959. else
  6960. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  6961. end;
  6962. end
  6963. else
  6964. InternalError(2020112330);
  6965. { Now go through every instruction we found and change the
  6966. size. If TargetSize = MaxSize, then almost no changes are
  6967. needed and Result can remain False if it hasn't been set
  6968. yet.
  6969. If RegChanged is True, then the register requires changing
  6970. and so the point about TargetSize = MaxSize doesn't apply. }
  6971. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  6972. begin
  6973. for Index := 0 to InstrMax do
  6974. begin
  6975. { If p_removed is true, then the original MOV/Z was removed
  6976. and removing the AND instruction may not be safe if it
  6977. appears first }
  6978. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6979. InternalError(2020112310);
  6980. if InstrList[Index].oper[0]^.typ = top_reg then
  6981. InstrList[Index].oper[0]^.reg := ThisReg;
  6982. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6983. InstrList[Index].opsize := TargetSize;
  6984. end;
  6985. Result := True;
  6986. end;
  6987. Exit;
  6988. end;
  6989. else
  6990. { This includes ADC, SBB, IDIV and SAR }
  6991. Break;
  6992. end;
  6993. if (TestValMin < 0) or (TestValMax < 0) or
  6994. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6995. { Overflow }
  6996. Break
  6997. else if not SmallerOverflow and (TrySmaller <> S_NO) and
  6998. ((TestValMin > TrySmallerLimit) or (TestValMax > TrySmallerLimit)) then
  6999. SmallerOverflow := True;
  7000. { Contains highest index (so instruction count - 1) }
  7001. Inc(InstrMax);
  7002. if InstrMax > High(InstrList) then
  7003. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  7004. InstrList[InstrMax] := taicpu(hp1);
  7005. end;
  7006. end;
  7007. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  7008. var
  7009. hp1 : tai;
  7010. begin
  7011. Result:=false;
  7012. if (taicpu(p).ops >= 2) and
  7013. ((taicpu(p).oper[0]^.typ = top_const) or
  7014. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  7015. (taicpu(p).oper[1]^.typ = top_reg) and
  7016. ((taicpu(p).ops = 2) or
  7017. ((taicpu(p).oper[2]^.typ = top_reg) and
  7018. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  7019. GetLastInstruction(p,hp1) and
  7020. MatchInstruction(hp1,A_MOV,[]) and
  7021. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7022. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7023. begin
  7024. TransferUsedRegs(TmpUsedRegs);
  7025. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  7026. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  7027. { change
  7028. mov reg1,reg2
  7029. imul y,reg2 to imul y,reg1,reg2 }
  7030. begin
  7031. taicpu(p).ops := 3;
  7032. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  7033. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7034. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  7035. RemoveInstruction(hp1);
  7036. result:=true;
  7037. end;
  7038. end;
  7039. end;
  7040. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  7041. var
  7042. ThisLabel: TAsmLabel;
  7043. begin
  7044. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  7045. ThisLabel.decrefs;
  7046. taicpu(p).opcode := A_RET;
  7047. taicpu(p).is_jmp := false;
  7048. taicpu(p).ops := taicpu(ret_p).ops;
  7049. case taicpu(ret_p).ops of
  7050. 0:
  7051. taicpu(p).clearop(0);
  7052. 1:
  7053. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  7054. else
  7055. internalerror(2016041301);
  7056. end;
  7057. { If the original label is now dead, it might turn out that the label
  7058. immediately follows p. As a result, everything beyond it, which will
  7059. be just some final register configuration and a RET instruction, is
  7060. now dead code. [Kit] }
  7061. { NOTE: This is much faster than introducing a OptPass2RET routine and
  7062. running RemoveDeadCodeAfterJump for each RET instruction, because
  7063. this optimisation rarely happens and most RETs appear at the end of
  7064. routines where there is nothing that can be stripped. [Kit] }
  7065. if not ThisLabel.is_used then
  7066. RemoveDeadCodeAfterJump(p);
  7067. end;
  7068. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  7069. var
  7070. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  7071. Unconditional, PotentialModified: Boolean;
  7072. OperPtr: POper;
  7073. NewRef: TReference;
  7074. InstrList: array of taicpu;
  7075. InstrMax, Index: Integer;
  7076. const
  7077. {$ifdef DEBUG_AOPTCPU}
  7078. SNoFlags: shortstring = ' so the flags aren''t modified';
  7079. {$else DEBUG_AOPTCPU}
  7080. SNoFlags = '';
  7081. {$endif DEBUG_AOPTCPU}
  7082. begin
  7083. Result:=false;
  7084. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  7085. begin
  7086. if MatchInstruction(hp1, A_TEST, [S_B]) and
  7087. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7088. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  7089. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  7090. GetNextInstruction(hp1, hp2) and
  7091. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  7092. { Change from: To:
  7093. set(C) %reg j(~C) label
  7094. test %reg,%reg/cmp $0,%reg
  7095. je label
  7096. set(C) %reg j(C) label
  7097. test %reg,%reg/cmp $0,%reg
  7098. jne label
  7099. (Also do something similar with sete/setne instead of je/jne)
  7100. }
  7101. begin
  7102. { Before we do anything else, we need to check the instructions
  7103. in between SETcc and TEST to make sure they don't modify the
  7104. FLAGS register - if -O2 or under, there won't be any
  7105. instructions between SET and TEST }
  7106. TransferUsedRegs(TmpUsedRegs);
  7107. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7108. if (cs_opt_level3 in current_settings.optimizerswitches) then
  7109. begin
  7110. next := p;
  7111. SetLength(InstrList, 0);
  7112. InstrMax := -1;
  7113. PotentialModified := False;
  7114. { Make a note of every instruction that modifies the FLAGS
  7115. register }
  7116. while GetNextInstruction(next, next) and (next <> hp1) do
  7117. begin
  7118. if next.typ <> ait_instruction then
  7119. { GetNextInstructionUsingReg should have returned False }
  7120. InternalError(2021051701);
  7121. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  7122. begin
  7123. case taicpu(next).opcode of
  7124. A_SETcc,
  7125. A_CMOVcc,
  7126. A_Jcc:
  7127. begin
  7128. if PotentialModified then
  7129. { Not safe because the flags were modified earlier }
  7130. Exit
  7131. else
  7132. { Condition is the same as the initial SETcc, so this is safe
  7133. (don't add to instruction list though) }
  7134. Continue;
  7135. end;
  7136. A_ADD:
  7137. begin
  7138. if (taicpu(next).opsize = S_B) or
  7139. { LEA doesn't support 8-bit operands }
  7140. (taicpu(next).oper[1]^.typ <> top_reg) or
  7141. { Must write to a register }
  7142. (taicpu(next).oper[0]^.typ = top_ref) then
  7143. { Require a constant or a register }
  7144. Exit;
  7145. PotentialModified := True;
  7146. end;
  7147. A_SUB:
  7148. begin
  7149. if (taicpu(next).opsize = S_B) or
  7150. { LEA doesn't support 8-bit operands }
  7151. (taicpu(next).oper[1]^.typ <> top_reg) or
  7152. { Must write to a register }
  7153. (taicpu(next).oper[0]^.typ <> top_const) or
  7154. (taicpu(next).oper[0]^.val = $80000000) then
  7155. { Can't subtract a register with LEA - also
  7156. check that the value isn't -2^31, as this
  7157. can't be negated }
  7158. Exit;
  7159. PotentialModified := True;
  7160. end;
  7161. A_SAL,
  7162. A_SHL:
  7163. begin
  7164. if (taicpu(next).opsize = S_B) or
  7165. { LEA doesn't support 8-bit operands }
  7166. (taicpu(next).oper[1]^.typ <> top_reg) or
  7167. { Must write to a register }
  7168. (taicpu(next).oper[0]^.typ <> top_const) or
  7169. (taicpu(next).oper[0]^.val < 0) or
  7170. (taicpu(next).oper[0]^.val > 3) then
  7171. Exit;
  7172. PotentialModified := True;
  7173. end;
  7174. A_IMUL:
  7175. begin
  7176. if (taicpu(next).ops <> 3) or
  7177. (taicpu(next).oper[1]^.typ <> top_reg) or
  7178. { Must write to a register }
  7179. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  7180. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  7181. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  7182. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  7183. Exit
  7184. else
  7185. PotentialModified := True;
  7186. end;
  7187. else
  7188. { Don't know how to change this, so abort }
  7189. Exit;
  7190. end;
  7191. { Contains highest index (so instruction count - 1) }
  7192. Inc(InstrMax);
  7193. if InstrMax > High(InstrList) then
  7194. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  7195. InstrList[InstrMax] := taicpu(next);
  7196. end;
  7197. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  7198. end;
  7199. if not Assigned(next) or (next <> hp1) then
  7200. { It should be equal to hp1 }
  7201. InternalError(2021051702);
  7202. { Cycle through each instruction and check to see if we can
  7203. change them to versions that don't modify the flags }
  7204. if (InstrMax >= 0) then
  7205. begin
  7206. for Index := 0 to InstrMax do
  7207. case InstrList[Index].opcode of
  7208. A_ADD:
  7209. begin
  7210. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  7211. InstrList[Index].opcode := A_LEA;
  7212. reference_reset(NewRef, 1, []);
  7213. NewRef.base := InstrList[Index].oper[1]^.reg;
  7214. if InstrList[Index].oper[0]^.typ = top_reg then
  7215. begin
  7216. NewRef.index := InstrList[Index].oper[0]^.reg;
  7217. NewRef.scalefactor := 1;
  7218. end
  7219. else
  7220. NewRef.offset := InstrList[Index].oper[0]^.val;
  7221. InstrList[Index].loadref(0, NewRef);
  7222. end;
  7223. A_SUB:
  7224. begin
  7225. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  7226. InstrList[Index].opcode := A_LEA;
  7227. reference_reset(NewRef, 1, []);
  7228. NewRef.base := InstrList[Index].oper[1]^.reg;
  7229. NewRef.offset := -InstrList[Index].oper[0]^.val;
  7230. InstrList[Index].loadref(0, NewRef);
  7231. end;
  7232. A_SHL,
  7233. A_SAL:
  7234. begin
  7235. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  7236. InstrList[Index].opcode := A_LEA;
  7237. reference_reset(NewRef, 1, []);
  7238. NewRef.index := InstrList[Index].oper[1]^.reg;
  7239. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  7240. InstrList[Index].loadref(0, NewRef);
  7241. end;
  7242. A_IMUL:
  7243. begin
  7244. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  7245. InstrList[Index].opcode := A_LEA;
  7246. reference_reset(NewRef, 1, []);
  7247. NewRef.index := InstrList[Index].oper[1]^.reg;
  7248. case InstrList[Index].oper[0]^.val of
  7249. 2, 4, 8:
  7250. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  7251. else {3, 5 and 9}
  7252. begin
  7253. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  7254. NewRef.base := InstrList[Index].oper[1]^.reg;
  7255. end;
  7256. end;
  7257. InstrList[Index].loadref(0, NewRef);
  7258. end;
  7259. else
  7260. InternalError(2021051710);
  7261. end;
  7262. end;
  7263. { Mark the FLAGS register as used across this whole block }
  7264. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  7265. end;
  7266. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  7267. JumpC := taicpu(hp2).condition;
  7268. Unconditional := False;
  7269. if conditions_equal(JumpC, C_E) then
  7270. SetC := inverse_cond(taicpu(p).condition)
  7271. else if conditions_equal(JumpC, C_NE) then
  7272. SetC := taicpu(p).condition
  7273. else
  7274. { We've got something weird here (and inefficent) }
  7275. begin
  7276. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  7277. SetC := C_NONE;
  7278. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  7279. if condition_in(C_AE, JumpC) then
  7280. Unconditional := True
  7281. else
  7282. { Not sure what to do with this jump - drop out }
  7283. Exit;
  7284. end;
  7285. RemoveInstruction(hp1);
  7286. if Unconditional then
  7287. MakeUnconditional(taicpu(hp2))
  7288. else
  7289. begin
  7290. if SetC = C_NONE then
  7291. InternalError(2018061402);
  7292. taicpu(hp2).SetCondition(SetC);
  7293. end;
  7294. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  7295. TmpUsedRegs }
  7296. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  7297. begin
  7298. RemoveCurrentp(p, hp2);
  7299. if taicpu(hp2).opcode = A_SETcc then
  7300. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  7301. else
  7302. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  7303. end
  7304. else
  7305. if taicpu(hp2).opcode = A_SETcc then
  7306. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  7307. else
  7308. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  7309. Result := True;
  7310. end
  7311. else if
  7312. { Make sure the instructions are adjacent }
  7313. (
  7314. not (cs_opt_level3 in current_settings.optimizerswitches) or
  7315. GetNextInstruction(p, hp1)
  7316. ) and
  7317. MatchInstruction(hp1, A_MOV, [S_B]) and
  7318. { Writing to memory is allowed }
  7319. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  7320. begin
  7321. {
  7322. Watch out for sequences such as:
  7323. set(c)b %regb
  7324. movb %regb,(ref)
  7325. movb $0,1(ref)
  7326. movb $0,2(ref)
  7327. movb $0,3(ref)
  7328. Much more efficient to turn it into:
  7329. movl $0,%regl
  7330. set(c)b %regb
  7331. movl %regl,(ref)
  7332. Or:
  7333. set(c)b %regb
  7334. movzbl %regb,%regl
  7335. movl %regl,(ref)
  7336. }
  7337. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  7338. GetNextInstruction(hp1, hp2) and
  7339. MatchInstruction(hp2, A_MOV, [S_B]) and
  7340. (taicpu(hp2).oper[1]^.typ = top_ref) and
  7341. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  7342. begin
  7343. { Don't do anything else except set Result to True }
  7344. end
  7345. else
  7346. begin
  7347. if taicpu(p).oper[0]^.typ = top_reg then
  7348. begin
  7349. TransferUsedRegs(TmpUsedRegs);
  7350. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7351. end;
  7352. { If it's not a register, it's a memory address }
  7353. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  7354. begin
  7355. { Even if the register is still in use, we can minimise the
  7356. pipeline stall by changing the MOV into another SETcc. }
  7357. taicpu(hp1).opcode := A_SETcc;
  7358. taicpu(hp1).condition := taicpu(p).condition;
  7359. if taicpu(hp1).oper[1]^.typ = top_ref then
  7360. begin
  7361. { Swapping the operand pointers like this is probably a
  7362. bit naughty, but it is far faster than using loadoper
  7363. to transfer the reference from oper[1] to oper[0] if
  7364. you take into account the extra procedure calls and
  7365. the memory allocation and deallocation required }
  7366. OperPtr := taicpu(hp1).oper[1];
  7367. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  7368. taicpu(hp1).oper[0] := OperPtr;
  7369. end
  7370. else
  7371. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  7372. taicpu(hp1).clearop(1);
  7373. taicpu(hp1).ops := 1;
  7374. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  7375. end
  7376. else
  7377. begin
  7378. if taicpu(hp1).oper[1]^.typ = top_reg then
  7379. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  7380. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7381. RemoveInstruction(hp1);
  7382. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  7383. end
  7384. end;
  7385. Result := True;
  7386. end;
  7387. end;
  7388. end;
  7389. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  7390. var
  7391. hp1: tai;
  7392. Count: Integer;
  7393. OrigLabel: TAsmLabel;
  7394. begin
  7395. result := False;
  7396. { Sometimes, the optimisations below can permit this }
  7397. RemoveDeadCodeAfterJump(p);
  7398. 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
  7399. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  7400. begin
  7401. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7402. { Also a side-effect of optimisations }
  7403. if CollapseZeroDistJump(p, OrigLabel) then
  7404. begin
  7405. Result := True;
  7406. Exit;
  7407. end;
  7408. hp1 := GetLabelWithSym(OrigLabel);
  7409. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  7410. begin
  7411. case taicpu(hp1).opcode of
  7412. A_RET:
  7413. {
  7414. change
  7415. jmp .L1
  7416. ...
  7417. .L1:
  7418. ret
  7419. into
  7420. ret
  7421. }
  7422. begin
  7423. ConvertJumpToRET(p, hp1);
  7424. result:=true;
  7425. end;
  7426. { Check any kind of direct assignment instruction }
  7427. A_MOV,
  7428. A_MOVD,
  7429. A_MOVQ,
  7430. A_MOVSX,
  7431. {$ifdef x86_64}
  7432. A_MOVSXD,
  7433. {$endif x86_64}
  7434. A_MOVZX,
  7435. A_MOVAPS,
  7436. A_MOVUPS,
  7437. A_MOVSD,
  7438. A_MOVAPD,
  7439. A_MOVUPD,
  7440. A_MOVDQA,
  7441. A_MOVDQU,
  7442. A_VMOVSS,
  7443. A_VMOVAPS,
  7444. A_VMOVUPS,
  7445. A_VMOVSD,
  7446. A_VMOVAPD,
  7447. A_VMOVUPD,
  7448. A_VMOVDQA,
  7449. A_VMOVDQU:
  7450. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  7451. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  7452. begin
  7453. Result := True;
  7454. Exit;
  7455. end;
  7456. else
  7457. ;
  7458. end;
  7459. end;
  7460. end;
  7461. end;
  7462. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  7463. begin
  7464. CanBeCMOV:=assigned(p) and
  7465. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  7466. { we can't use cmov ref,reg because
  7467. ref could be nil and cmov still throws an exception
  7468. if ref=nil but the mov isn't done (FK)
  7469. or ((taicpu(p).oper[0]^.typ = top_ref) and
  7470. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  7471. }
  7472. (taicpu(p).oper[1]^.typ = top_reg) and
  7473. (
  7474. (taicpu(p).oper[0]^.typ = top_reg) or
  7475. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  7476. it is not expected that this can cause a seg. violation }
  7477. (
  7478. (taicpu(p).oper[0]^.typ = top_ref) and
  7479. IsRefSafe(taicpu(p).oper[0]^.ref)
  7480. )
  7481. );
  7482. end;
  7483. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  7484. var
  7485. hp1,hp2: tai;
  7486. {$ifndef i8086}
  7487. hp3,hp4,hpmov2, hp5: tai;
  7488. l : Longint;
  7489. condition : TAsmCond;
  7490. {$endif i8086}
  7491. carryadd_opcode : TAsmOp;
  7492. symbol: TAsmSymbol;
  7493. reg: tsuperregister;
  7494. increg, tmpreg: TRegister;
  7495. begin
  7496. result:=false;
  7497. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  7498. begin
  7499. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7500. if (
  7501. (
  7502. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  7503. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  7504. (Taicpu(hp1).oper[0]^.val=1)
  7505. ) or
  7506. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  7507. ) and
  7508. GetNextInstruction(hp1,hp2) and
  7509. SkipAligns(hp2, hp2) and
  7510. (hp2.typ = ait_label) and
  7511. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  7512. { jb @@1 cmc
  7513. inc/dec operand --> adc/sbb operand,0
  7514. @@1:
  7515. ... and ...
  7516. jnb @@1
  7517. inc/dec operand --> adc/sbb operand,0
  7518. @@1: }
  7519. begin
  7520. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  7521. begin
  7522. case taicpu(hp1).opcode of
  7523. A_INC,
  7524. A_ADD:
  7525. carryadd_opcode:=A_ADC;
  7526. A_DEC,
  7527. A_SUB:
  7528. carryadd_opcode:=A_SBB;
  7529. else
  7530. InternalError(2021011001);
  7531. end;
  7532. Taicpu(p).clearop(0);
  7533. Taicpu(p).ops:=0;
  7534. Taicpu(p).is_jmp:=false;
  7535. Taicpu(p).opcode:=A_CMC;
  7536. Taicpu(p).condition:=C_NONE;
  7537. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  7538. Taicpu(hp1).ops:=2;
  7539. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  7540. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7541. else
  7542. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7543. Taicpu(hp1).loadconst(0,0);
  7544. Taicpu(hp1).opcode:=carryadd_opcode;
  7545. result:=true;
  7546. exit;
  7547. end
  7548. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  7549. begin
  7550. case taicpu(hp1).opcode of
  7551. A_INC,
  7552. A_ADD:
  7553. carryadd_opcode:=A_ADC;
  7554. A_DEC,
  7555. A_SUB:
  7556. carryadd_opcode:=A_SBB;
  7557. else
  7558. InternalError(2021011002);
  7559. end;
  7560. Taicpu(hp1).ops:=2;
  7561. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  7562. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  7563. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7564. else
  7565. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7566. Taicpu(hp1).loadconst(0,0);
  7567. Taicpu(hp1).opcode:=carryadd_opcode;
  7568. RemoveCurrentP(p, hp1);
  7569. result:=true;
  7570. exit;
  7571. end
  7572. {
  7573. jcc @@1 setcc tmpreg
  7574. inc/dec/add/sub operand -> (movzx tmpreg)
  7575. @@1: add/sub tmpreg,operand
  7576. While this increases code size slightly, it makes the code much faster if the
  7577. jump is unpredictable
  7578. }
  7579. else if not(cs_opt_size in current_settings.optimizerswitches) then
  7580. begin
  7581. { search for an available register which is volatile }
  7582. for reg in tcpuregisterset do
  7583. begin
  7584. if
  7585. {$if defined(i386) or defined(i8086)}
  7586. { Only use registers whose lowest 8-bits can Be accessed }
  7587. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  7588. {$endif i386 or i8086}
  7589. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  7590. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  7591. { We don't need to check if tmpreg is in hp1 or not, because
  7592. it will be marked as in use at p (if not, this is
  7593. indictive of a compiler bug). }
  7594. then
  7595. begin
  7596. TAsmLabel(symbol).decrefs;
  7597. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  7598. Taicpu(p).clearop(0);
  7599. Taicpu(p).ops:=1;
  7600. Taicpu(p).is_jmp:=false;
  7601. Taicpu(p).opcode:=A_SETcc;
  7602. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  7603. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  7604. Taicpu(p).loadreg(0,increg);
  7605. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  7606. begin
  7607. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  7608. R_SUBW:
  7609. begin
  7610. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  7611. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  7612. end;
  7613. R_SUBD:
  7614. begin
  7615. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  7616. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  7617. end;
  7618. {$ifdef x86_64}
  7619. R_SUBQ:
  7620. begin
  7621. { MOVZX doesn't have a 64-bit variant, because
  7622. the 32-bit version implicitly zeroes the
  7623. upper 32-bits of the destination register }
  7624. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  7625. newreg(R_INTREGISTER,reg,R_SUBD));
  7626. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  7627. end;
  7628. {$endif x86_64}
  7629. else
  7630. Internalerror(2020030601);
  7631. end;
  7632. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  7633. asml.InsertAfter(hp2,p);
  7634. end
  7635. else
  7636. tmpreg := increg;
  7637. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  7638. begin
  7639. Taicpu(hp1).ops:=2;
  7640. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  7641. end;
  7642. Taicpu(hp1).loadreg(0,tmpreg);
  7643. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  7644. Result := True;
  7645. { p is no longer a Jcc instruction, so exit }
  7646. Exit;
  7647. end;
  7648. end;
  7649. end;
  7650. end;
  7651. { Detect the following:
  7652. jmp<cond> @Lbl1
  7653. jmp @Lbl2
  7654. ...
  7655. @Lbl1:
  7656. ret
  7657. Change to:
  7658. jmp<inv_cond> @Lbl2
  7659. ret
  7660. }
  7661. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  7662. begin
  7663. hp2:=getlabelwithsym(TAsmLabel(symbol));
  7664. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  7665. MatchInstruction(hp2,A_RET,[S_NO]) then
  7666. begin
  7667. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7668. { Change label address to that of the unconditional jump }
  7669. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  7670. TAsmLabel(symbol).DecRefs;
  7671. taicpu(hp1).opcode := A_RET;
  7672. taicpu(hp1).is_jmp := false;
  7673. taicpu(hp1).ops := taicpu(hp2).ops;
  7674. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  7675. case taicpu(hp2).ops of
  7676. 0:
  7677. taicpu(hp1).clearop(0);
  7678. 1:
  7679. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  7680. else
  7681. internalerror(2016041302);
  7682. end;
  7683. end;
  7684. {$ifndef i8086}
  7685. end
  7686. {
  7687. convert
  7688. j<c> .L1
  7689. mov 1,reg
  7690. jmp .L2
  7691. .L1
  7692. mov 0,reg
  7693. .L2
  7694. into
  7695. mov 0,reg
  7696. set<not(c)> reg
  7697. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7698. would destroy the flag contents
  7699. }
  7700. else if MatchInstruction(hp1,A_MOV,[]) and
  7701. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7702. {$ifdef i386}
  7703. (
  7704. { Under i386, ESI, EDI, EBP and ESP
  7705. don't have an 8-bit representation }
  7706. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7707. ) and
  7708. {$endif i386}
  7709. (taicpu(hp1).oper[0]^.val=1) and
  7710. GetNextInstruction(hp1,hp2) and
  7711. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7712. GetNextInstruction(hp2,hp3) and
  7713. { skip align }
  7714. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  7715. (hp3.typ=ait_label) and
  7716. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7717. (tai_label(hp3).labsym.getrefs=1) and
  7718. GetNextInstruction(hp3,hp4) and
  7719. MatchInstruction(hp4,A_MOV,[]) and
  7720. MatchOpType(taicpu(hp4),top_const,top_reg) and
  7721. (taicpu(hp4).oper[0]^.val=0) and
  7722. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7723. GetNextInstruction(hp4,hp5) and
  7724. (hp5.typ=ait_label) and
  7725. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  7726. (tai_label(hp5).labsym.getrefs=1) then
  7727. begin
  7728. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  7729. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  7730. { remove last label }
  7731. RemoveInstruction(hp5);
  7732. { remove second label }
  7733. RemoveInstruction(hp3);
  7734. { if align is present remove it }
  7735. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  7736. RemoveInstruction(hp3);
  7737. { remove jmp }
  7738. RemoveInstruction(hp2);
  7739. if taicpu(hp1).opsize=S_B then
  7740. RemoveInstruction(hp1)
  7741. else
  7742. taicpu(hp1).loadconst(0,0);
  7743. taicpu(hp4).opcode:=A_SETcc;
  7744. taicpu(hp4).opsize:=S_B;
  7745. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  7746. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  7747. taicpu(hp4).opercnt:=1;
  7748. taicpu(hp4).ops:=1;
  7749. taicpu(hp4).freeop(1);
  7750. RemoveCurrentP(p);
  7751. Result:=true;
  7752. exit;
  7753. end
  7754. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  7755. begin
  7756. { check for
  7757. jCC xxx
  7758. <several movs>
  7759. xxx:
  7760. }
  7761. l:=0;
  7762. while assigned(hp1) and
  7763. CanBeCMOV(hp1) and
  7764. { stop on labels }
  7765. not(hp1.typ=ait_label) do
  7766. begin
  7767. inc(l);
  7768. GetNextInstruction(hp1,hp1);
  7769. end;
  7770. if assigned(hp1) then
  7771. begin
  7772. if FindLabel(tasmlabel(symbol),hp1) then
  7773. begin
  7774. if (l<=4) and (l>0) then
  7775. begin
  7776. condition:=inverse_cond(taicpu(p).condition);
  7777. GetNextInstruction(p,hp1);
  7778. repeat
  7779. if not Assigned(hp1) then
  7780. InternalError(2018062900);
  7781. taicpu(hp1).opcode:=A_CMOVcc;
  7782. taicpu(hp1).condition:=condition;
  7783. UpdateUsedRegs(hp1);
  7784. GetNextInstruction(hp1,hp1);
  7785. until not(CanBeCMOV(hp1));
  7786. { Remember what hp1 is in case there's multiple aligns to get rid of }
  7787. hp2 := hp1;
  7788. repeat
  7789. if not Assigned(hp2) then
  7790. InternalError(2018062910);
  7791. case hp2.typ of
  7792. ait_label:
  7793. { What we expected - break out of the loop (it won't be a dead label at the top of
  7794. a cluster because that was optimised at an earlier stage) }
  7795. Break;
  7796. ait_align:
  7797. { Go to the next entry until a label is found (may be multiple aligns before it) }
  7798. begin
  7799. hp2 := tai(hp2.Next);
  7800. Continue;
  7801. end;
  7802. else
  7803. begin
  7804. { Might be a comment or temporary allocation entry }
  7805. if not (hp2.typ in SkipInstr) then
  7806. InternalError(2018062911);
  7807. hp2 := tai(hp2.Next);
  7808. Continue;
  7809. end;
  7810. end;
  7811. until False;
  7812. { Now we can safely decrement the reference count }
  7813. tasmlabel(symbol).decrefs;
  7814. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  7815. { Remove the original jump }
  7816. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  7817. GetNextInstruction(hp2, p); { Instruction after the label }
  7818. { Remove the label if this is its final reference }
  7819. if (tasmlabel(symbol).getrefs=0) then
  7820. StripLabelFast(hp1);
  7821. if Assigned(p) then
  7822. begin
  7823. UpdateUsedRegs(p);
  7824. result:=true;
  7825. end;
  7826. exit;
  7827. end;
  7828. end
  7829. else
  7830. begin
  7831. { check further for
  7832. jCC xxx
  7833. <several movs 1>
  7834. jmp yyy
  7835. xxx:
  7836. <several movs 2>
  7837. yyy:
  7838. }
  7839. { hp2 points to jmp yyy }
  7840. hp2:=hp1;
  7841. { skip hp1 to xxx (or an align right before it) }
  7842. GetNextInstruction(hp1, hp1);
  7843. if assigned(hp2) and
  7844. assigned(hp1) and
  7845. (l<=3) and
  7846. (hp2.typ=ait_instruction) and
  7847. (taicpu(hp2).is_jmp) and
  7848. (taicpu(hp2).condition=C_None) and
  7849. { real label and jump, no further references to the
  7850. label are allowed }
  7851. (tasmlabel(symbol).getrefs=1) and
  7852. FindLabel(tasmlabel(symbol),hp1) then
  7853. begin
  7854. l:=0;
  7855. { skip hp1 to <several moves 2> }
  7856. if (hp1.typ = ait_align) then
  7857. GetNextInstruction(hp1, hp1);
  7858. GetNextInstruction(hp1, hpmov2);
  7859. hp1 := hpmov2;
  7860. while assigned(hp1) and
  7861. CanBeCMOV(hp1) do
  7862. begin
  7863. inc(l);
  7864. GetNextInstruction(hp1, hp1);
  7865. end;
  7866. { hp1 points to yyy (or an align right before it) }
  7867. hp3 := hp1;
  7868. if assigned(hp1) and
  7869. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  7870. begin
  7871. condition:=inverse_cond(taicpu(p).condition);
  7872. GetNextInstruction(p,hp1);
  7873. repeat
  7874. taicpu(hp1).opcode:=A_CMOVcc;
  7875. taicpu(hp1).condition:=condition;
  7876. UpdateUsedRegs(hp1);
  7877. GetNextInstruction(hp1,hp1);
  7878. until not(assigned(hp1)) or
  7879. not(CanBeCMOV(hp1));
  7880. condition:=inverse_cond(condition);
  7881. hp1 := hpmov2;
  7882. { hp1 is now at <several movs 2> }
  7883. while Assigned(hp1) and CanBeCMOV(hp1) do
  7884. begin
  7885. taicpu(hp1).opcode:=A_CMOVcc;
  7886. taicpu(hp1).condition:=condition;
  7887. UpdateUsedRegs(hp1);
  7888. GetNextInstruction(hp1,hp1);
  7889. end;
  7890. hp1 := p;
  7891. { Get first instruction after label }
  7892. GetNextInstruction(hp3, p);
  7893. if assigned(p) and (hp3.typ = ait_align) then
  7894. GetNextInstruction(p, p);
  7895. { Don't dereference yet, as doing so will cause
  7896. GetNextInstruction to skip the label and
  7897. optional align marker. [Kit] }
  7898. GetNextInstruction(hp2, hp4);
  7899. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  7900. { remove jCC }
  7901. RemoveInstruction(hp1);
  7902. { Now we can safely decrement it }
  7903. tasmlabel(symbol).decrefs;
  7904. { Remove label xxx (it will have a ref of zero due to the initial check }
  7905. StripLabelFast(hp4);
  7906. { remove jmp }
  7907. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  7908. RemoveInstruction(hp2);
  7909. { As before, now we can safely decrement it }
  7910. tasmlabel(symbol).decrefs;
  7911. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  7912. if tasmlabel(symbol).getrefs = 0 then
  7913. StripLabelFast(hp3);
  7914. if Assigned(p) then
  7915. begin
  7916. UpdateUsedRegs(p);
  7917. result:=true;
  7918. end;
  7919. exit;
  7920. end;
  7921. end;
  7922. end;
  7923. end;
  7924. {$endif i8086}
  7925. end;
  7926. end;
  7927. end;
  7928. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  7929. var
  7930. hp1,hp2: tai;
  7931. reg_and_hp1_is_instr: Boolean;
  7932. begin
  7933. result:=false;
  7934. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  7935. GetNextInstruction(p,hp1) and
  7936. (hp1.typ = ait_instruction);
  7937. if reg_and_hp1_is_instr and
  7938. (
  7939. (taicpu(hp1).opcode <> A_LEA) or
  7940. { If the LEA instruction can be converted into an arithmetic instruction,
  7941. it may be possible to then fold it. }
  7942. (
  7943. { If the flags register is in use, don't change the instruction
  7944. to an ADD otherwise this will scramble the flags. [Kit] }
  7945. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  7946. ConvertLEA(taicpu(hp1))
  7947. )
  7948. ) and
  7949. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  7950. GetNextInstruction(hp1,hp2) and
  7951. MatchInstruction(hp2,A_MOV,[]) and
  7952. (taicpu(hp2).oper[0]^.typ = top_reg) and
  7953. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  7954. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  7955. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  7956. {$ifdef i386}
  7957. { not all registers have byte size sub registers on i386 }
  7958. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  7959. {$endif i386}
  7960. (((taicpu(hp1).ops=2) and
  7961. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7962. ((taicpu(hp1).ops=1) and
  7963. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  7964. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  7965. begin
  7966. { change movsX/movzX reg/ref, reg2
  7967. add/sub/or/... reg3/$const, reg2
  7968. mov reg2 reg/ref
  7969. to add/sub/or/... reg3/$const, reg/ref }
  7970. { by example:
  7971. movswl %si,%eax movswl %si,%eax p
  7972. decl %eax addl %edx,%eax hp1
  7973. movw %ax,%si movw %ax,%si hp2
  7974. ->
  7975. movswl %si,%eax movswl %si,%eax p
  7976. decw %eax addw %edx,%eax hp1
  7977. movw %ax,%si movw %ax,%si hp2
  7978. }
  7979. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  7980. {
  7981. ->
  7982. movswl %si,%eax movswl %si,%eax p
  7983. decw %si addw %dx,%si hp1
  7984. movw %ax,%si movw %ax,%si hp2
  7985. }
  7986. case taicpu(hp1).ops of
  7987. 1:
  7988. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  7989. 2:
  7990. begin
  7991. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  7992. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7993. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  7994. end;
  7995. else
  7996. internalerror(2008042702);
  7997. end;
  7998. {
  7999. ->
  8000. decw %si addw %dx,%si p
  8001. }
  8002. DebugMsg(SPeepholeOptimization + 'var3',p);
  8003. RemoveCurrentP(p, hp1);
  8004. RemoveInstruction(hp2);
  8005. end
  8006. else if reg_and_hp1_is_instr and
  8007. (taicpu(hp1).opcode = A_MOV) and
  8008. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8009. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  8010. {$ifdef x86_64}
  8011. { check for implicit extension to 64 bit }
  8012. or
  8013. ((taicpu(p).opsize in [S_BL,S_WL]) and
  8014. (taicpu(hp1).opsize=S_Q) and
  8015. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  8016. )
  8017. {$endif x86_64}
  8018. )
  8019. then
  8020. begin
  8021. { change
  8022. movx %reg1,%reg2
  8023. mov %reg2,%reg3
  8024. dealloc %reg2
  8025. into
  8026. movx %reg,%reg3
  8027. }
  8028. TransferUsedRegs(TmpUsedRegs);
  8029. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8030. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8031. begin
  8032. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  8033. {$ifdef x86_64}
  8034. if (taicpu(p).opsize in [S_BL,S_WL]) and
  8035. (taicpu(hp1).opsize=S_Q) then
  8036. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  8037. else
  8038. {$endif x86_64}
  8039. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8040. RemoveInstruction(hp1);
  8041. end;
  8042. end
  8043. else if reg_and_hp1_is_instr and
  8044. (taicpu(hp1).opcode = A_MOV) and
  8045. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8046. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  8047. (taicpu(hp1).opsize=S_B)) or
  8048. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  8049. (taicpu(hp1).opsize=S_W))
  8050. {$ifdef x86_64}
  8051. or ((taicpu(p).opsize=S_LQ) and
  8052. (taicpu(hp1).opsize=S_L))
  8053. {$endif x86_64}
  8054. ) and
  8055. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  8056. begin
  8057. { change
  8058. movx %reg1,%reg2
  8059. mov %reg2,%reg3
  8060. dealloc %reg2
  8061. into
  8062. mov %reg1,%reg3
  8063. if the second mov accesses only the bits stored in reg1
  8064. }
  8065. TransferUsedRegs(TmpUsedRegs);
  8066. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8067. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8068. begin
  8069. DebugMsg(SPeepholeOptimization + 'MovxMov2Mov',p);
  8070. if taicpu(p).oper[0]^.typ=top_reg then
  8071. begin
  8072. case taicpu(hp1).opsize of
  8073. S_B:
  8074. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  8075. S_W:
  8076. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  8077. S_L:
  8078. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  8079. else
  8080. Internalerror(2020102301);
  8081. end;
  8082. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  8083. end
  8084. else
  8085. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  8086. RemoveCurrentP(p);
  8087. result:=true;
  8088. exit;
  8089. end;
  8090. end
  8091. else if reg_and_hp1_is_instr and
  8092. (taicpu(p).oper[0]^.typ = top_reg) and
  8093. (
  8094. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  8095. ) and
  8096. (taicpu(hp1).oper[0]^.typ = top_const) and
  8097. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8098. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8099. { Minimum shift value allowed is the bit difference between the sizes }
  8100. (taicpu(hp1).oper[0]^.val >=
  8101. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  8102. 8 * (
  8103. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  8104. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  8105. )
  8106. ) then
  8107. begin
  8108. { For:
  8109. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  8110. shl/sal ##, %reg1
  8111. Remove the movsx/movzx instruction if the shift overwrites the
  8112. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  8113. }
  8114. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  8115. RemoveCurrentP(p, hp1);
  8116. Result := True;
  8117. Exit;
  8118. end
  8119. else if reg_and_hp1_is_instr and
  8120. (taicpu(p).oper[0]^.typ = top_reg) and
  8121. (
  8122. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  8123. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  8124. ) and
  8125. (taicpu(hp1).oper[0]^.typ = top_const) and
  8126. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8127. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8128. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  8129. (taicpu(hp1).oper[0]^.val <
  8130. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  8131. 8 * (
  8132. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  8133. )
  8134. ) then
  8135. begin
  8136. { For:
  8137. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  8138. sar ##, %reg1 shr ##, %reg1
  8139. Move the shift to before the movx instruction if the shift value
  8140. is not too large.
  8141. }
  8142. asml.Remove(hp1);
  8143. asml.InsertBefore(hp1, p);
  8144. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  8145. case taicpu(p).opsize of
  8146. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  8147. taicpu(hp1).opsize := S_B;
  8148. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  8149. taicpu(hp1).opsize := S_W;
  8150. {$ifdef x86_64}
  8151. S_LQ:
  8152. taicpu(hp1).opsize := S_L;
  8153. {$endif}
  8154. else
  8155. InternalError(2020112401);
  8156. end;
  8157. if (taicpu(hp1).opcode = A_SHR) then
  8158. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  8159. else
  8160. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  8161. Result := True;
  8162. end
  8163. else if taicpu(p).opcode=A_MOVZX then
  8164. begin
  8165. { removes superfluous And's after movzx's }
  8166. if reg_and_hp1_is_instr and
  8167. (taicpu(hp1).opcode = A_AND) and
  8168. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8169. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  8170. {$ifdef x86_64}
  8171. { check for implicit extension to 64 bit }
  8172. or
  8173. ((taicpu(p).opsize in [S_BL,S_WL]) and
  8174. (taicpu(hp1).opsize=S_Q) and
  8175. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  8176. )
  8177. {$endif x86_64}
  8178. )
  8179. then
  8180. begin
  8181. case taicpu(p).opsize Of
  8182. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8183. if (taicpu(hp1).oper[0]^.val = $ff) then
  8184. begin
  8185. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  8186. RemoveInstruction(hp1);
  8187. Result:=true;
  8188. exit;
  8189. end;
  8190. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8191. if (taicpu(hp1).oper[0]^.val = $ffff) then
  8192. begin
  8193. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  8194. RemoveInstruction(hp1);
  8195. Result:=true;
  8196. exit;
  8197. end;
  8198. {$ifdef x86_64}
  8199. S_LQ:
  8200. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  8201. begin
  8202. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  8203. RemoveInstruction(hp1);
  8204. Result:=true;
  8205. exit;
  8206. end;
  8207. {$endif x86_64}
  8208. else
  8209. ;
  8210. end;
  8211. { we cannot get rid of the and, but can we get rid of the movz ?}
  8212. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  8213. begin
  8214. case taicpu(p).opsize Of
  8215. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8216. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  8217. begin
  8218. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  8219. RemoveCurrentP(p,hp1);
  8220. Result:=true;
  8221. exit;
  8222. end;
  8223. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8224. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  8225. begin
  8226. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  8227. RemoveCurrentP(p,hp1);
  8228. Result:=true;
  8229. exit;
  8230. end;
  8231. {$ifdef x86_64}
  8232. S_LQ:
  8233. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  8234. begin
  8235. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  8236. RemoveCurrentP(p,hp1);
  8237. Result:=true;
  8238. exit;
  8239. end;
  8240. {$endif x86_64}
  8241. else
  8242. ;
  8243. end;
  8244. end;
  8245. end;
  8246. { changes some movzx constructs to faster synonyms (all examples
  8247. are given with eax/ax, but are also valid for other registers)}
  8248. if MatchOpType(taicpu(p),top_reg,top_reg) then
  8249. begin
  8250. case taicpu(p).opsize of
  8251. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  8252. (the machine code is equivalent to movzbl %al,%eax), but the
  8253. code generator still generates that assembler instruction and
  8254. it is silently converted. This should probably be checked.
  8255. [Kit] }
  8256. S_BW:
  8257. begin
  8258. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8259. (
  8260. not IsMOVZXAcceptable
  8261. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  8262. or (
  8263. (cs_opt_size in current_settings.optimizerswitches) and
  8264. (taicpu(p).oper[1]^.reg = NR_AX)
  8265. )
  8266. ) then
  8267. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  8268. begin
  8269. DebugMsg(SPeepholeOptimization + 'var7',p);
  8270. taicpu(p).opcode := A_AND;
  8271. taicpu(p).changeopsize(S_W);
  8272. taicpu(p).loadConst(0,$ff);
  8273. Result := True;
  8274. end
  8275. else if not IsMOVZXAcceptable and
  8276. GetNextInstruction(p, hp1) and
  8277. (tai(hp1).typ = ait_instruction) and
  8278. (taicpu(hp1).opcode = A_AND) and
  8279. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8280. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8281. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  8282. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  8283. begin
  8284. DebugMsg(SPeepholeOptimization + 'var8',p);
  8285. taicpu(p).opcode := A_MOV;
  8286. taicpu(p).changeopsize(S_W);
  8287. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  8288. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8289. Result := True;
  8290. end;
  8291. end;
  8292. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  8293. S_BL:
  8294. begin
  8295. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8296. (
  8297. not IsMOVZXAcceptable
  8298. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  8299. or (
  8300. (cs_opt_size in current_settings.optimizerswitches) and
  8301. (taicpu(p).oper[1]^.reg = NR_EAX)
  8302. )
  8303. ) then
  8304. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  8305. begin
  8306. DebugMsg(SPeepholeOptimization + 'var9',p);
  8307. taicpu(p).opcode := A_AND;
  8308. taicpu(p).changeopsize(S_L);
  8309. taicpu(p).loadConst(0,$ff);
  8310. Result := True;
  8311. end
  8312. else if not IsMOVZXAcceptable and
  8313. GetNextInstruction(p, hp1) and
  8314. (tai(hp1).typ = ait_instruction) and
  8315. (taicpu(hp1).opcode = A_AND) and
  8316. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8317. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8318. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  8319. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  8320. begin
  8321. DebugMsg(SPeepholeOptimization + 'var10',p);
  8322. taicpu(p).opcode := A_MOV;
  8323. taicpu(p).changeopsize(S_L);
  8324. { do not use R_SUBWHOLE
  8325. as movl %rdx,%eax
  8326. is invalid in assembler PM }
  8327. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8328. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8329. Result := True;
  8330. end;
  8331. end;
  8332. {$endif i8086}
  8333. S_WL:
  8334. if not IsMOVZXAcceptable then
  8335. begin
  8336. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  8337. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  8338. begin
  8339. DebugMsg(SPeepholeOptimization + 'var11',p);
  8340. taicpu(p).opcode := A_AND;
  8341. taicpu(p).changeopsize(S_L);
  8342. taicpu(p).loadConst(0,$ffff);
  8343. Result := True;
  8344. end
  8345. else if GetNextInstruction(p, hp1) and
  8346. (tai(hp1).typ = ait_instruction) and
  8347. (taicpu(hp1).opcode = A_AND) and
  8348. (taicpu(hp1).oper[0]^.typ = top_const) and
  8349. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8350. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8351. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  8352. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  8353. begin
  8354. DebugMsg(SPeepholeOptimization + 'var12',p);
  8355. taicpu(p).opcode := A_MOV;
  8356. taicpu(p).changeopsize(S_L);
  8357. { do not use R_SUBWHOLE
  8358. as movl %rdx,%eax
  8359. is invalid in assembler PM }
  8360. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  8361. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  8362. Result := True;
  8363. end;
  8364. end;
  8365. else
  8366. InternalError(2017050705);
  8367. end;
  8368. end
  8369. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  8370. begin
  8371. if GetNextInstruction(p, hp1) and
  8372. (tai(hp1).typ = ait_instruction) and
  8373. (taicpu(hp1).opcode = A_AND) and
  8374. MatchOpType(taicpu(hp1),top_const,top_reg) and
  8375. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8376. begin
  8377. //taicpu(p).opcode := A_MOV;
  8378. case taicpu(p).opsize Of
  8379. S_BL:
  8380. begin
  8381. DebugMsg(SPeepholeOptimization + 'var13',p);
  8382. taicpu(hp1).changeopsize(S_L);
  8383. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8384. end;
  8385. S_WL:
  8386. begin
  8387. DebugMsg(SPeepholeOptimization + 'var14',p);
  8388. taicpu(hp1).changeopsize(S_L);
  8389. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  8390. end;
  8391. S_BW:
  8392. begin
  8393. DebugMsg(SPeepholeOptimization + 'var15',p);
  8394. taicpu(hp1).changeopsize(S_W);
  8395. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  8396. end;
  8397. else
  8398. Internalerror(2017050704)
  8399. end;
  8400. Result := True;
  8401. end;
  8402. end;
  8403. end;
  8404. end;
  8405. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  8406. var
  8407. hp1, hp2 : tai;
  8408. MaskLength : Cardinal;
  8409. MaskedBits : TCgInt;
  8410. begin
  8411. Result:=false;
  8412. { There are no optimisations for reference targets }
  8413. if (taicpu(p).oper[1]^.typ <> top_reg) then
  8414. Exit;
  8415. while GetNextInstruction(p, hp1) and
  8416. (hp1.typ = ait_instruction) do
  8417. begin
  8418. if (taicpu(p).oper[0]^.typ = top_const) then
  8419. begin
  8420. case taicpu(hp1).opcode of
  8421. A_AND:
  8422. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8423. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8424. { the second register must contain the first one, so compare their subreg types }
  8425. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  8426. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  8427. { change
  8428. and const1, reg
  8429. and const2, reg
  8430. to
  8431. and (const1 and const2), reg
  8432. }
  8433. begin
  8434. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  8435. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  8436. RemoveCurrentP(p, hp1);
  8437. Result:=true;
  8438. exit;
  8439. end;
  8440. A_CMP:
  8441. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  8442. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  8443. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8444. { Just check that the condition on the next instruction is compatible }
  8445. GetNextInstruction(hp1, hp2) and
  8446. (hp2.typ = ait_instruction) and
  8447. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  8448. then
  8449. { change
  8450. and 2^n, reg
  8451. cmp 2^n, reg
  8452. j(c) / set(c) / cmov(c) (c is equal or not equal)
  8453. to
  8454. and 2^n, reg
  8455. test reg, reg
  8456. j(~c) / set(~c) / cmov(~c)
  8457. }
  8458. begin
  8459. { Keep TEST instruction in, rather than remove it, because
  8460. it may trigger other optimisations such as MovAndTest2Test }
  8461. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  8462. taicpu(hp1).opcode := A_TEST;
  8463. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  8464. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  8465. Result := True;
  8466. Exit;
  8467. end;
  8468. A_MOVZX:
  8469. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8470. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  8471. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8472. (
  8473. (
  8474. (taicpu(p).opsize=S_W) and
  8475. (taicpu(hp1).opsize=S_BW)
  8476. ) or
  8477. (
  8478. (taicpu(p).opsize=S_L) and
  8479. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  8480. )
  8481. {$ifdef x86_64}
  8482. or
  8483. (
  8484. (taicpu(p).opsize=S_Q) and
  8485. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  8486. )
  8487. {$endif x86_64}
  8488. ) then
  8489. begin
  8490. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8491. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  8492. ) or
  8493. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8494. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  8495. then
  8496. begin
  8497. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  8498. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  8499. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  8500. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  8501. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  8502. }
  8503. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  8504. RemoveInstruction(hp1);
  8505. { See if there are other optimisations possible }
  8506. Continue;
  8507. end;
  8508. end;
  8509. A_SHL:
  8510. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8511. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8512. begin
  8513. {$ifopt R+}
  8514. {$define RANGE_WAS_ON}
  8515. {$R-}
  8516. {$endif}
  8517. { get length of potential and mask }
  8518. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  8519. { really a mask? }
  8520. {$ifdef RANGE_WAS_ON}
  8521. {$R+}
  8522. {$endif}
  8523. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  8524. { unmasked part shifted out? }
  8525. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  8526. begin
  8527. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  8528. RemoveCurrentP(p, hp1);
  8529. Result:=true;
  8530. exit;
  8531. end;
  8532. end;
  8533. A_SHR:
  8534. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8535. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  8536. (taicpu(hp1).oper[0]^.val <= 63) then
  8537. begin
  8538. { Does SHR combined with the AND cover all the bits?
  8539. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  8540. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  8541. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  8542. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  8543. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  8544. begin
  8545. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  8546. RemoveCurrentP(p, hp1);
  8547. Result := True;
  8548. Exit;
  8549. end;
  8550. end;
  8551. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8552. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  8553. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  8554. begin
  8555. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8556. (
  8557. (
  8558. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8559. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  8560. ) or (
  8561. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8562. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  8563. {$ifdef x86_64}
  8564. ) or (
  8565. (taicpu(hp1).opsize = S_LQ) and
  8566. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  8567. {$endif x86_64}
  8568. )
  8569. ) then
  8570. begin
  8571. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  8572. begin
  8573. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  8574. RemoveInstruction(hp1);
  8575. { See if there are other optimisations possible }
  8576. Continue;
  8577. end;
  8578. { The super-registers are the same though.
  8579. Note that this change by itself doesn't improve
  8580. code speed, but it opens up other optimisations. }
  8581. {$ifdef x86_64}
  8582. { Convert 64-bit register to 32-bit }
  8583. case taicpu(hp1).opsize of
  8584. S_BQ:
  8585. begin
  8586. taicpu(hp1).opsize := S_BL;
  8587. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8588. end;
  8589. S_WQ:
  8590. begin
  8591. taicpu(hp1).opsize := S_WL;
  8592. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8593. end
  8594. else
  8595. ;
  8596. end;
  8597. {$endif x86_64}
  8598. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  8599. taicpu(hp1).opcode := A_MOVZX;
  8600. { See if there are other optimisations possible }
  8601. Continue;
  8602. end;
  8603. end;
  8604. else
  8605. ;
  8606. end;
  8607. end;
  8608. if (taicpu(hp1).is_jmp) and
  8609. (taicpu(hp1).opcode<>A_JMP) and
  8610. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  8611. begin
  8612. { change
  8613. and x, reg
  8614. jxx
  8615. to
  8616. test x, reg
  8617. jxx
  8618. if reg is deallocated before the
  8619. jump, but only if it's a conditional jump (PFV)
  8620. }
  8621. taicpu(p).opcode := A_TEST;
  8622. Exit;
  8623. end;
  8624. Break;
  8625. end;
  8626. { Lone AND tests }
  8627. if (taicpu(p).oper[0]^.typ = top_const) then
  8628. begin
  8629. {
  8630. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  8631. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  8632. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  8633. }
  8634. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  8635. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  8636. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  8637. begin
  8638. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  8639. if taicpu(p).opsize = S_L then
  8640. begin
  8641. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  8642. Result := True;
  8643. end;
  8644. end;
  8645. end;
  8646. { Backward check to determine necessity of and %reg,%reg }
  8647. if (taicpu(p).oper[0]^.typ = top_reg) and
  8648. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  8649. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  8650. GetLastInstruction(p, hp2) and
  8651. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  8652. { Check size of adjacent instruction to determine if the AND is
  8653. effectively a null operation }
  8654. (
  8655. (taicpu(p).opsize = taicpu(hp2).opsize) or
  8656. { Note: Don't include S_Q }
  8657. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  8658. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  8659. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  8660. ) then
  8661. begin
  8662. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  8663. { If GetNextInstruction returned False, hp1 will be nil }
  8664. RemoveCurrentP(p, hp1);
  8665. Result := True;
  8666. Exit;
  8667. end;
  8668. end;
  8669. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  8670. var
  8671. hp1: tai; NewRef: TReference;
  8672. { This entire nested function is used in an if-statement below, but we
  8673. want to avoid all the used reg transfers and GetNextInstruction calls
  8674. until we really have to check }
  8675. function MemRegisterNotUsedLater: Boolean; inline;
  8676. var
  8677. hp2: tai;
  8678. begin
  8679. TransferUsedRegs(TmpUsedRegs);
  8680. hp2 := p;
  8681. repeat
  8682. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8683. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8684. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  8685. end;
  8686. begin
  8687. Result := False;
  8688. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  8689. Exit;
  8690. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  8691. begin
  8692. { Change:
  8693. add %reg2,%reg1
  8694. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  8695. To:
  8696. mov/s/z #(%reg1,%reg2),%reg1
  8697. }
  8698. if MatchOpType(taicpu(p), top_reg, top_reg) and
  8699. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  8700. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  8701. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  8702. (
  8703. (
  8704. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  8705. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  8706. { r/esp cannot be an index }
  8707. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  8708. ) or (
  8709. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  8710. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  8711. )
  8712. ) and (
  8713. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  8714. (
  8715. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  8716. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8717. MemRegisterNotUsedLater
  8718. )
  8719. ) then
  8720. begin
  8721. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  8722. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  8723. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  8724. RemoveCurrentp(p, hp1);
  8725. Result := True;
  8726. Exit;
  8727. end;
  8728. { Change:
  8729. addl/q $x,%reg1
  8730. movl/q %reg1,%reg2
  8731. To:
  8732. leal/q $x(%reg1),%reg2
  8733. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8734. Breaks the dependency chain.
  8735. }
  8736. if MatchOpType(taicpu(p),top_const,top_reg) and
  8737. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8738. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8739. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8740. (
  8741. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  8742. not (cs_opt_size in current_settings.optimizerswitches) or
  8743. (
  8744. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8745. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8746. )
  8747. ) then
  8748. begin
  8749. { Change the MOV instruction to a LEA instruction, and update the
  8750. first operand }
  8751. reference_reset(NewRef, 1, []);
  8752. NewRef.base := taicpu(p).oper[1]^.reg;
  8753. NewRef.scalefactor := 1;
  8754. NewRef.offset := taicpu(p).oper[0]^.val;
  8755. taicpu(hp1).opcode := A_LEA;
  8756. taicpu(hp1).loadref(0, NewRef);
  8757. TransferUsedRegs(TmpUsedRegs);
  8758. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8759. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8760. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8761. begin
  8762. { Move what is now the LEA instruction to before the SUB instruction }
  8763. Asml.Remove(hp1);
  8764. Asml.InsertBefore(hp1, p);
  8765. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8766. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  8767. p := hp1;
  8768. end
  8769. else
  8770. begin
  8771. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8772. RemoveCurrentP(p, hp1);
  8773. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  8774. end;
  8775. Result := True;
  8776. end;
  8777. end;
  8778. end;
  8779. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  8780. begin
  8781. Result:=false;
  8782. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8783. begin
  8784. if MatchReference(taicpu(p).oper[0]^.ref^,taicpu(p).oper[1]^.reg,NR_INVALID) and
  8785. (taicpu(p).oper[0]^.ref^.index<>NR_NO) then
  8786. begin
  8787. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.base);
  8788. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.index);
  8789. taicpu(p).opcode:=A_ADD;
  8790. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  8791. result:=true;
  8792. end
  8793. else if MatchReference(taicpu(p).oper[0]^.ref^,NR_INVALID,taicpu(p).oper[1]^.reg) and
  8794. (taicpu(p).oper[0]^.ref^.base<>NR_NO) then
  8795. begin
  8796. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.index);
  8797. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.base);
  8798. taicpu(p).opcode:=A_ADD;
  8799. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  8800. result:=true;
  8801. end;
  8802. end;
  8803. end;
  8804. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  8805. var
  8806. hp1: tai; NewRef: TReference;
  8807. begin
  8808. { Change:
  8809. subl/q $x,%reg1
  8810. movl/q %reg1,%reg2
  8811. To:
  8812. leal/q $-x(%reg1),%reg2
  8813. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8814. Breaks the dependency chain and potentially permits the removal of
  8815. a CMP instruction if one follows.
  8816. }
  8817. Result := False;
  8818. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8819. MatchOpType(taicpu(p),top_const,top_reg) and
  8820. GetNextInstruction(p, hp1) and
  8821. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8822. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8823. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8824. (
  8825. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  8826. not (cs_opt_size in current_settings.optimizerswitches) or
  8827. (
  8828. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8829. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8830. )
  8831. ) then
  8832. begin
  8833. { Change the MOV instruction to a LEA instruction, and update the
  8834. first operand }
  8835. reference_reset(NewRef, 1, []);
  8836. NewRef.base := taicpu(p).oper[1]^.reg;
  8837. NewRef.scalefactor := 1;
  8838. NewRef.offset := -taicpu(p).oper[0]^.val;
  8839. taicpu(hp1).opcode := A_LEA;
  8840. taicpu(hp1).loadref(0, NewRef);
  8841. TransferUsedRegs(TmpUsedRegs);
  8842. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8843. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8844. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8845. begin
  8846. { Move what is now the LEA instruction to before the SUB instruction }
  8847. Asml.Remove(hp1);
  8848. Asml.InsertBefore(hp1, p);
  8849. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8850. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  8851. p := hp1;
  8852. end
  8853. else
  8854. begin
  8855. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8856. RemoveCurrentP(p, hp1);
  8857. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  8858. end;
  8859. Result := True;
  8860. end;
  8861. end;
  8862. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  8863. begin
  8864. { we can skip all instructions not messing with the stack pointer }
  8865. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  8866. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  8867. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  8868. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  8869. ({(taicpu(hp1).ops=0) or }
  8870. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  8871. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  8872. ) and }
  8873. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  8874. )
  8875. ) do
  8876. GetNextInstruction(hp1,hp1);
  8877. Result:=assigned(hp1);
  8878. end;
  8879. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  8880. var
  8881. hp1, hp2, hp3, hp4, hp5: tai;
  8882. begin
  8883. Result:=false;
  8884. hp5:=nil;
  8885. { replace
  8886. leal(q) x(<stackpointer>),<stackpointer>
  8887. call procname
  8888. leal(q) -x(<stackpointer>),<stackpointer>
  8889. ret
  8890. by
  8891. jmp procname
  8892. but do it only on level 4 because it destroys stack back traces
  8893. }
  8894. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8895. MatchOpType(taicpu(p),top_ref,top_reg) and
  8896. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8897. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  8898. { the -8 or -24 are not required, but bail out early if possible,
  8899. higher values are unlikely }
  8900. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  8901. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  8902. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  8903. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  8904. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  8905. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8906. GetNextInstruction(p, hp1) and
  8907. { Take a copy of hp1 }
  8908. SetAndTest(hp1, hp4) and
  8909. { trick to skip label }
  8910. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8911. SkipSimpleInstructions(hp1) and
  8912. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8913. GetNextInstruction(hp1, hp2) and
  8914. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  8915. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  8916. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  8917. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8918. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  8919. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  8920. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  8921. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  8922. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8923. GetNextInstruction(hp2, hp3) and
  8924. { trick to skip label }
  8925. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8926. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8927. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8928. SetAndTest(hp3,hp5) and
  8929. GetNextInstruction(hp3,hp3) and
  8930. MatchInstruction(hp3,A_RET,[S_NO])
  8931. )
  8932. ) and
  8933. (taicpu(hp3).ops=0) then
  8934. begin
  8935. taicpu(hp1).opcode := A_JMP;
  8936. taicpu(hp1).is_jmp := true;
  8937. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  8938. RemoveCurrentP(p, hp4);
  8939. RemoveInstruction(hp2);
  8940. RemoveInstruction(hp3);
  8941. if Assigned(hp5) then
  8942. begin
  8943. AsmL.Remove(hp5);
  8944. ASmL.InsertBefore(hp5,hp1)
  8945. end;
  8946. Result:=true;
  8947. end;
  8948. end;
  8949. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  8950. {$ifdef x86_64}
  8951. var
  8952. hp1, hp2, hp3, hp4, hp5: tai;
  8953. {$endif x86_64}
  8954. begin
  8955. Result:=false;
  8956. {$ifdef x86_64}
  8957. hp5:=nil;
  8958. { replace
  8959. push %rax
  8960. call procname
  8961. pop %rcx
  8962. ret
  8963. by
  8964. jmp procname
  8965. but do it only on level 4 because it destroys stack back traces
  8966. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  8967. for all supported calling conventions
  8968. }
  8969. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8970. MatchOpType(taicpu(p),top_reg) and
  8971. (taicpu(p).oper[0]^.reg=NR_RAX) and
  8972. GetNextInstruction(p, hp1) and
  8973. { Take a copy of hp1 }
  8974. SetAndTest(hp1, hp4) and
  8975. { trick to skip label }
  8976. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8977. SkipSimpleInstructions(hp1) and
  8978. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8979. GetNextInstruction(hp1, hp2) and
  8980. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  8981. MatchOpType(taicpu(hp2),top_reg) and
  8982. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  8983. GetNextInstruction(hp2, hp3) and
  8984. { trick to skip label }
  8985. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8986. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8987. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8988. SetAndTest(hp3,hp5) and
  8989. GetNextInstruction(hp3,hp3) and
  8990. MatchInstruction(hp3,A_RET,[S_NO])
  8991. )
  8992. ) and
  8993. (taicpu(hp3).ops=0) then
  8994. begin
  8995. taicpu(hp1).opcode := A_JMP;
  8996. taicpu(hp1).is_jmp := true;
  8997. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  8998. RemoveCurrentP(p, hp4);
  8999. RemoveInstruction(hp2);
  9000. RemoveInstruction(hp3);
  9001. if Assigned(hp5) then
  9002. begin
  9003. AsmL.Remove(hp5);
  9004. ASmL.InsertBefore(hp5,hp1)
  9005. end;
  9006. Result:=true;
  9007. end;
  9008. {$endif x86_64}
  9009. end;
  9010. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  9011. var
  9012. Value, RegName: string;
  9013. begin
  9014. Result:=false;
  9015. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  9016. begin
  9017. case taicpu(p).oper[0]^.val of
  9018. 0:
  9019. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  9020. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  9021. begin
  9022. { change "mov $0,%reg" into "xor %reg,%reg" }
  9023. taicpu(p).opcode := A_XOR;
  9024. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  9025. Result := True;
  9026. {$ifdef x86_64}
  9027. end
  9028. else if (taicpu(p).opsize = S_Q) then
  9029. begin
  9030. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  9031. { The actual optimization }
  9032. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9033. taicpu(p).changeopsize(S_L);
  9034. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  9035. Result := True;
  9036. end;
  9037. $1..$FFFFFFFF:
  9038. begin
  9039. { Code size reduction by J. Gareth "Kit" Moreton }
  9040. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  9041. case taicpu(p).opsize of
  9042. S_Q:
  9043. begin
  9044. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  9045. Value := debug_tostr(taicpu(p).oper[0]^.val);
  9046. { The actual optimization }
  9047. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9048. taicpu(p).changeopsize(S_L);
  9049. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  9050. Result := True;
  9051. end;
  9052. else
  9053. { Do nothing };
  9054. end;
  9055. {$endif x86_64}
  9056. end;
  9057. -1:
  9058. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  9059. if (cs_opt_size in current_settings.optimizerswitches) and
  9060. (taicpu(p).opsize <> S_B) and
  9061. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  9062. begin
  9063. { change "mov $-1,%reg" into "or $-1,%reg" }
  9064. { NOTES:
  9065. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  9066. - This operation creates a false dependency on the register, so only do it when optimising for size
  9067. - 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
  9068. }
  9069. taicpu(p).opcode := A_OR;
  9070. Result := True;
  9071. end;
  9072. else
  9073. { Do nothing };
  9074. end;
  9075. end;
  9076. end;
  9077. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  9078. var
  9079. hp1: tai;
  9080. begin
  9081. { Detect:
  9082. andw x, %ax (0 <= x < $8000)
  9083. ...
  9084. movzwl %ax,%eax
  9085. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  9086. }
  9087. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  9088. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  9089. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  9090. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  9091. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  9092. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  9093. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  9094. begin
  9095. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  9096. taicpu(hp1).opcode := A_CWDE;
  9097. taicpu(hp1).clearop(0);
  9098. taicpu(hp1).clearop(1);
  9099. taicpu(hp1).ops := 0;
  9100. { A change was made, but not with p, so move forward 1 }
  9101. p := tai(p.Next);
  9102. Result := True;
  9103. end;
  9104. end;
  9105. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  9106. begin
  9107. Result := False;
  9108. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  9109. Exit;
  9110. { Convert:
  9111. movswl %ax,%eax -> cwtl
  9112. movslq %eax,%rax -> cdqe
  9113. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  9114. refer to the same opcode and depends only on the assembler's
  9115. current operand-size attribute. [Kit]
  9116. }
  9117. with taicpu(p) do
  9118. case opsize of
  9119. S_WL:
  9120. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  9121. begin
  9122. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  9123. opcode := A_CWDE;
  9124. clearop(0);
  9125. clearop(1);
  9126. ops := 0;
  9127. Result := True;
  9128. end;
  9129. {$ifdef x86_64}
  9130. S_LQ:
  9131. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  9132. begin
  9133. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  9134. opcode := A_CDQE;
  9135. clearop(0);
  9136. clearop(1);
  9137. ops := 0;
  9138. Result := True;
  9139. end;
  9140. {$endif x86_64}
  9141. else
  9142. ;
  9143. end;
  9144. end;
  9145. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  9146. var
  9147. hp1: tai;
  9148. begin
  9149. { Detect:
  9150. shr x, %ax (x > 0)
  9151. ...
  9152. movzwl %ax,%eax
  9153. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  9154. }
  9155. Result := False;
  9156. if MatchOpType(taicpu(p), top_const, top_reg) and
  9157. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  9158. (taicpu(p).oper[0]^.val > 0) and
  9159. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  9160. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  9161. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  9162. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  9163. begin
  9164. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  9165. taicpu(hp1).opcode := A_CWDE;
  9166. taicpu(hp1).clearop(0);
  9167. taicpu(hp1).clearop(1);
  9168. taicpu(hp1).ops := 0;
  9169. { A change was made, but not with p, so move forward 1 }
  9170. p := tai(p.Next);
  9171. Result := True;
  9172. end;
  9173. end;
  9174. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  9175. begin
  9176. Result:=false;
  9177. { change "cmp $0, %reg" to "test %reg, %reg" }
  9178. if MatchOpType(taicpu(p),top_const,top_reg) and
  9179. (taicpu(p).oper[0]^.val = 0) then
  9180. begin
  9181. taicpu(p).opcode := A_TEST;
  9182. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  9183. Result:=true;
  9184. end;
  9185. end;
  9186. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  9187. var
  9188. IsTestConstX : Boolean;
  9189. hp1,hp2 : tai;
  9190. begin
  9191. Result:=false;
  9192. { removes the line marked with (x) from the sequence
  9193. and/or/xor/add/sub/... $x, %y
  9194. test/or %y, %y | test $-1, %y (x)
  9195. j(n)z _Label
  9196. as the first instruction already adjusts the ZF
  9197. %y operand may also be a reference }
  9198. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  9199. MatchOperand(taicpu(p).oper[0]^,-1);
  9200. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  9201. GetLastInstruction(p, hp1) and
  9202. (tai(hp1).typ = ait_instruction) and
  9203. GetNextInstruction(p,hp2) and
  9204. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  9205. case taicpu(hp1).opcode Of
  9206. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  9207. begin
  9208. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  9209. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9210. { and in case of carry for A(E)/B(E)/C/NC }
  9211. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  9212. ((taicpu(hp1).opcode <> A_ADD) and
  9213. (taicpu(hp1).opcode <> A_SUB))) then
  9214. begin
  9215. RemoveCurrentP(p, hp2);
  9216. Result:=true;
  9217. Exit;
  9218. end;
  9219. end;
  9220. A_SHL, A_SAL, A_SHR, A_SAR:
  9221. begin
  9222. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  9223. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  9224. { therefore, it's only safe to do this optimization for }
  9225. { shifts by a (nonzero) constant }
  9226. (taicpu(hp1).oper[0]^.typ = top_const) and
  9227. (taicpu(hp1).oper[0]^.val <> 0) and
  9228. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9229. { and in case of carry for A(E)/B(E)/C/NC }
  9230. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  9231. begin
  9232. RemoveCurrentP(p, hp2);
  9233. Result:=true;
  9234. Exit;
  9235. end;
  9236. end;
  9237. A_DEC, A_INC, A_NEG:
  9238. begin
  9239. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  9240. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  9241. { and in case of carry for A(E)/B(E)/C/NC }
  9242. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  9243. begin
  9244. RemoveCurrentP(p, hp2);
  9245. Result:=true;
  9246. Exit;
  9247. end;
  9248. end
  9249. else
  9250. ;
  9251. end; { case }
  9252. { change "test $-1,%reg" into "test %reg,%reg" }
  9253. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  9254. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  9255. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  9256. if MatchInstruction(p, A_OR, []) and
  9257. { Can only match if they're both registers }
  9258. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  9259. begin
  9260. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  9261. taicpu(p).opcode := A_TEST;
  9262. { No need to set Result to True, as we've done all the optimisations we can }
  9263. end;
  9264. end;
  9265. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  9266. var
  9267. hp1,hp3 : tai;
  9268. {$ifndef x86_64}
  9269. hp2 : taicpu;
  9270. {$endif x86_64}
  9271. begin
  9272. Result:=false;
  9273. hp3:=nil;
  9274. {$ifndef x86_64}
  9275. { don't do this on modern CPUs, this really hurts them due to
  9276. broken call/ret pairing }
  9277. if (current_settings.optimizecputype < cpu_Pentium2) and
  9278. not(cs_create_pic in current_settings.moduleswitches) and
  9279. GetNextInstruction(p, hp1) and
  9280. MatchInstruction(hp1,A_JMP,[S_NO]) and
  9281. MatchOpType(taicpu(hp1),top_ref) and
  9282. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9283. begin
  9284. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  9285. InsertLLItem(p.previous, p, hp2);
  9286. taicpu(p).opcode := A_JMP;
  9287. taicpu(p).is_jmp := true;
  9288. RemoveInstruction(hp1);
  9289. Result:=true;
  9290. end
  9291. else
  9292. {$endif x86_64}
  9293. { replace
  9294. call procname
  9295. ret
  9296. by
  9297. jmp procname
  9298. but do it only on level 4 because it destroys stack back traces
  9299. else if the subroutine is marked as no return, remove the ret
  9300. }
  9301. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  9302. (po_noreturn in current_procinfo.procdef.procoptions)) and
  9303. GetNextInstruction(p, hp1) and
  9304. (MatchInstruction(hp1,A_RET,[S_NO]) or
  9305. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  9306. SetAndTest(hp1,hp3) and
  9307. GetNextInstruction(hp1,hp1) and
  9308. MatchInstruction(hp1,A_RET,[S_NO])
  9309. )
  9310. ) and
  9311. (taicpu(hp1).ops=0) then
  9312. begin
  9313. if (cs_opt_level4 in current_settings.optimizerswitches) and
  9314. { we might destroy stack alignment here if we do not do a call }
  9315. (target_info.stackalign<=sizeof(SizeUInt)) then
  9316. begin
  9317. taicpu(p).opcode := A_JMP;
  9318. taicpu(p).is_jmp := true;
  9319. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  9320. end
  9321. else
  9322. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  9323. RemoveInstruction(hp1);
  9324. if Assigned(hp3) then
  9325. begin
  9326. AsmL.Remove(hp3);
  9327. AsmL.InsertBefore(hp3,p)
  9328. end;
  9329. Result:=true;
  9330. end;
  9331. end;
  9332. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  9333. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  9334. begin
  9335. case OpSize of
  9336. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9337. Result := (Val <= $FF) and (Val >= -128);
  9338. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9339. Result := (Val <= $FFFF) and (Val >= -32768);
  9340. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  9341. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  9342. else
  9343. Result := True;
  9344. end;
  9345. end;
  9346. var
  9347. hp1, hp2 : tai;
  9348. SizeChange: Boolean;
  9349. PreMessage: string;
  9350. begin
  9351. Result := False;
  9352. if (taicpu(p).oper[0]^.typ = top_reg) and
  9353. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9354. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  9355. begin
  9356. { Change (using movzbl %al,%eax as an example):
  9357. movzbl %al, %eax movzbl %al, %eax
  9358. cmpl x, %eax testl %eax,%eax
  9359. To:
  9360. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  9361. movzbl %al, %eax movzbl %al, %eax
  9362. Smaller instruction and minimises pipeline stall as the CPU
  9363. doesn't have to wait for the register to get zero-extended. [Kit]
  9364. Also allow if the smaller of the two registers is being checked,
  9365. as this still removes the false dependency.
  9366. }
  9367. if
  9368. (
  9369. (
  9370. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  9371. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  9372. ) or (
  9373. { If MatchOperand returns True, they must both be registers }
  9374. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  9375. )
  9376. ) and
  9377. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  9378. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  9379. begin
  9380. 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);
  9381. asml.Remove(hp1);
  9382. asml.InsertBefore(hp1, p);
  9383. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  9384. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  9385. begin
  9386. taicpu(hp1).opcode := A_TEST;
  9387. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  9388. end;
  9389. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  9390. case taicpu(p).opsize of
  9391. S_BW, S_BL:
  9392. begin
  9393. SizeChange := taicpu(hp1).opsize <> S_B;
  9394. taicpu(hp1).changeopsize(S_B);
  9395. end;
  9396. S_WL:
  9397. begin
  9398. SizeChange := taicpu(hp1).opsize <> S_W;
  9399. taicpu(hp1).changeopsize(S_W);
  9400. end
  9401. else
  9402. InternalError(2020112701);
  9403. end;
  9404. UpdateUsedRegs(tai(p.Next));
  9405. { Check if the register is used aferwards - if not, we can
  9406. remove the movzx instruction completely }
  9407. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9408. begin
  9409. { Hp1 is a better position than p for debugging purposes }
  9410. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  9411. RemoveCurrentp(p, hp1);
  9412. Result := True;
  9413. end;
  9414. if SizeChange then
  9415. DebugMsg(SPeepholeOptimization + PreMessage +
  9416. 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)
  9417. else
  9418. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  9419. Exit;
  9420. end;
  9421. { Change (using movzwl %ax,%eax as an example):
  9422. movzwl %ax, %eax
  9423. movb %al, (dest) (Register is smaller than read register in movz)
  9424. To:
  9425. movb %al, (dest) (Move one back to avoid a false dependency)
  9426. movzwl %ax, %eax
  9427. }
  9428. if (taicpu(hp1).opcode = A_MOV) and
  9429. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9430. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  9431. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  9432. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  9433. begin
  9434. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  9435. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  9436. asml.Remove(hp1);
  9437. asml.InsertBefore(hp1, p);
  9438. if taicpu(hp1).oper[1]^.typ = top_reg then
  9439. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  9440. { Check if the register is used aferwards - if not, we can
  9441. remove the movzx instruction completely }
  9442. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  9443. begin
  9444. { Hp1 is a better position than p for debugging purposes }
  9445. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  9446. RemoveCurrentp(p, hp1);
  9447. Result := True;
  9448. end;
  9449. Exit;
  9450. end;
  9451. end;
  9452. end;
  9453. {$ifdef x86_64}
  9454. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  9455. var
  9456. PreMessage, RegName: string;
  9457. begin
  9458. { Code size reduction by J. Gareth "Kit" Moreton }
  9459. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  9460. as this removes the REX prefix }
  9461. Result := False;
  9462. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  9463. Exit;
  9464. if taicpu(p).oper[0]^.typ <> top_reg then
  9465. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  9466. InternalError(2018011500);
  9467. case taicpu(p).opsize of
  9468. S_Q:
  9469. begin
  9470. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  9471. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  9472. { The actual optimization }
  9473. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  9474. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9475. taicpu(p).changeopsize(S_L);
  9476. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  9477. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  9478. end;
  9479. else
  9480. ;
  9481. end;
  9482. end;
  9483. {$endif}
  9484. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  9485. var
  9486. OperIdx: Integer;
  9487. begin
  9488. for OperIdx := 0 to p.ops - 1 do
  9489. if p.oper[OperIdx]^.typ = top_ref then
  9490. optimize_ref(p.oper[OperIdx]^.ref^, False);
  9491. end;
  9492. end.